from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q, Count, F, Sum
import hashlib, requests, logging, re, json
from django.db import transaction
from django_redis import get_redis_connection
from django.conf import settings
from decimal import Decimal
from random import randint, shuffle
from django.db.models.expressions import RawSQL
from geopy.distance import geodesic
from elasticsearch import Elasticsearch

from merchants.serializers import *
from equity_mall.utils.pages import MyPage, BillPage
from merchants.filters import *
from equity_mall.utils.sync_img_to_local import sync_img_to_local, make_qrcode, make_qrcode1
from users.models import Level
from activities.models import Channel
from equity_mall.utils.qiniu_storage import pic_upload, pic_delete
from equity_mall.utils.common_msg import common_msg
from equity_mall.utils.utils import ryx_settle_order, get_sign, ryx_profitsharing_order, get_sign_contract_url, check_sign_contract_result
from users.models import User
from customers.utils import AlipayOpen as C_AlipayOpen
from customers.utils import pay_transactions_jsapi, pay_transactions_native
from merchants.tasks import *
from equity_admin.tasks import express_send
from vouchers.models import *
from merchants.utils import get_wyf_order_settle

logger = logging.getLogger('django')
ysh_merchant_logger = logging.getLogger('ysh_merchant')


class MerchantUserModelViewSet(ModelViewSet):

    def info(self, request):
        user = self.request.iser
        return Response(MerchantUserInfoSerializer(user).data, status=status.HTTP_200_OK)


class MerchantBillModelViewSet(ModelViewSet):

    pagination_class = BillPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = MerchantBillFilter

    def get_queryset(self):
        user = self.request.iser
        queryset = MerchantBill.objects.filter(merchant__merchantuser_id=user.id).order_by('-receipts_time')
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.request.query_params.get('page', '1')
        if page != '1':
            try:
                if '_mutable' in self.request.query_params.__dict__:
                    self.request.query_params.__dict__['_mutable'] = True
                self.request.query_params['date'] = queryset[(int(page)-1)*10-1].receipts_time.strftime("%Y-%m-%d")
            except:
                pass
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def get_serializer_class(self):
        if self.action == 'list':
            return MerchantBillListModelSerializer
        else:
            return MerchantBillRetrieveModelSerializer


class OrderInfoModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = OrderInfoFilter

    def get_queryset(self):
        user = self.request.iser
        search = self.request.query_params.get('search', None)
        queryset = OrderInfo.objects.filter(merchant__merchantuser_id=user.id, state__in=[1, 2, 3, 6, 9, 14, 5, 8])
        if search:
            es = Elasticsearch(["http://159.75.55.19:9200/"])
            body = {
                "query": {
                    "bool": {
                        "must": [],
                        "must_not": [],
                        "should": [],
                        # "filter": {
                        #     "ids": {
                        #         "values": ["orders.orderinfo.5418961"]
                        #     }
                        # }
                    }
                },
                "from": 0,
                "size": 10000,
                "sort": [],
                "aggs": {}
            }
            if not search.isdigit():
                filter_data = {
                    "match_phrase_prefix": {
                        "text": search
                    }
                }
                body['query']['bool']['must'].append(filter_data)
            else:
                filter_data = {
                    "wildcard": {
                        "text": f'*{search}*'
                    }
                }
                body['query']['bool']['must'].append(filter_data)
            merchant_set = Merchant.objects.filter(merchantuser_id=user.id)
            for merchant in merchant_set:
                filter_data = {
                    "wildcard": {
                        "text": merchant.wyfMerchantID
                    }
                }
                body['query']['bool']['should'].append(filter_data)
            result = es.search(index="equity_mall_order", doc_type="modelresult", body=body)
            # return Response(result)
            hits = result['hits']['hits']
            id_list = []
            for order in hits:
                id_list.append(order['_id'])
            queryset = queryset.filter(id__in=id_list)
        return queryset.order_by('-create_time')

    def get_serializer_class(self):
        if self.action == 'list':
            return OrderInfoListModelSerializer
        else:
            return OrderInfoRetrieveModelSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        order_count = len(queryset)
        order_amount = queryset.aggregate(Sum('total_price'))['total_price__sum']
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        self.request.data['order_count'] = str(order_count)
        self.request.data['order_amount'] = str(order_amount)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def check_coupon(self, request):
        user = self.request.iser
        coupon_id = self.request.data.get('coupon_id', None)
        if not coupon_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        coupon_id = str(coupon_id).replace('https://qrcode.sutpay.com/merchant/coupon/?sn=', '').replace('https://qrcode.sutpay.com/manager/coupon/?sn=', '')
        try:
            goodscoupon = GoodsCoupons.objects.get(coupons_id=coupon_id)
        except:
            return Response({'error': '无效核销码'}, status=status.HTTP_400_BAD_REQUEST)
        order = goodscoupon.order
        goods = goodscoupon.goods
        if goods.category_id != 1:
            return Response({'error': '核销码类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        if order.level_id:
            is_can = 0
            try:
                msg = f'*该订单属于{order.level.name}自提订单,您没有该商品的核销权限!'
            except:
                msg = f'*您没有该商品的核销权限!'
            coupon_arr = []
            coupon_list = []
        else:
            if goods.merchant.merchantuser_id != user.id:
                is_can = 0
                msg = f'*您没有该商品的核销权限!'
                coupon_arr = []
                coupon_list = []
            else:
                if goodscoupon.status == 1:
                    is_can = 1
                    msg = ''
                    coupon_arr = [coupon_id]
                    coupon_list = []
                else:
                    goodscoupons_set = GoodsCoupons.objects.filter(order_id=order.id, status=1).exclude(coupons_id=coupon_id)
                    if goodscoupons_set:
                        coupon_arr = []
                        coupon_list = []
                        for goodscoupons in goodscoupons_set:
                            coupon_arr.append(goodscoupons.coupons_id)
                            coupon_list.append({
                                'goods_name': goodscoupons.goods.name,
                                'price': goodscoupons.goods.price,
                                'count': 1
                            })
                        is_can = 2
                        msg = ''
                    else:
                        is_can = 0
                        if goodscoupon.status == 3:
                            msg = '**提货码已过期'
                        elif goodscoupon.status == 4:
                            msg = '**提货码已撤销'
                        else:
                            msg = ''
                        coupon_arr = []
                        coupon_list = []
        data = {}
        data['merchant_name'] = goods.merchant.managerName
        data['goods_name'] = goods.name
        data['default_image'] = goods.default_image.url
        data['count'] = 1
        data['price'] = goods.price
        data['create_time'] = order.create_time.strftime('%Y-%m-%d %H:%M:%S')
        if order.level:
            data['level_name'] = order.level.name
        else:
            data['level_name'] = '商家自营'
        data['mobile'] = order.reserved_mobile
        data['request_date'] = {'coupon_arr': coupon_arr, 'order_id': order.id}
        data['coupon_list'] = coupon_list
        data['is_can'] = is_can
        data['msg'] = msg
        data['status'] = goodscoupon.status
        data['status_str'] = goodscoupon.get_status_display()
        return Response(data, status=status.HTTP_200_OK)

    def use_coupon(self, request):
        user = self.request.iser
        coupon_arr = self.request.data.get('coupon_arr', None)
        order_id = self.request.data.get('order_id', None)
        if not all([coupon_arr, order_id]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if type(coupon_arr) != list:
            return Response({'error': '参数类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            order = OrderInfo.objects.get(id=order_id)
        except:
            return Response({'error': '无效订单号'}, status=status.HTTP_400_BAD_REQUEST)
        if order.order_type == 3:
            return Response({'error': '此核销码为兑换券类型,请在对应渠道使用'}, status=status.HTTP_400_BAD_REQUEST)
        if order.state != 2:
            return Response({'error': '订单已无未核销商品,请刷新核实'}, status=status.HTTP_400_BAD_REQUEST)
        if order.level_id:
            return Response({'error': f'该订单属于{order.level.name}自提订单,您没有该商品的核销权限!'}, status=status.HTTP_400_BAD_REQUEST)
        coupon_arr1 = []
        for coupon_id in coupon_arr:
            coupon_id = str(coupon_id).replace('https://qrcode.sutpay.com/merchant/coupon/?sn=', '').replace('https://qrcode.sutpay.com/manager/coupon/?sn=', '')
            coupon_arr1.append(coupon_id)
        goodscoupons_set = GoodsCoupons.objects.filter(coupons_id__in=coupon_arr1, order_id=order_id, status=1)
        for goodscoupons in goodscoupons_set:
            goods = goodscoupons.goods
            if goods.merchant.merchantuser_id != user.id:
                return Response({'error': '您无权核销该订单'}, status=status.HTTP_400_BAD_REQUEST)
        for goodscoupons in goodscoupons_set:
            goodscoupons.status = 2
            goodscoupons.use_time = datetime.datetime.now()
            goodscoupons.use_merchantuser_id = user.id
            goodscoupons.save()
        data = {}
        goodscoupons_set = GoodsCoupons.objects.filter(order_id=order_id, status=1)
        if not goodscoupons_set:
            order.state = 3
            order.use_time = datetime.datetime.now()
            order.merchantuser_id = user.id
            order.save()
            if order.order_type in [1, 7]:
                result = '初始值'
                try:
                    # ordergoods_set = order.ordergoods_set.all().filter(goods__is_settlement=1)
                    # context = ''
                    # for ordergoods in ordergoods_set:
                    #     context = context + f'{ordergoods.goods.name}*{ordergoods.count},'
                    #     receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                    #     bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=ordergoods.merchant_id, bill_type=order.order_species).first()
                    #     if not bill:
                    #         bill_data = {}
                    #         bill_data['merchant_id'] = ordergoods.merchant_id
                    #         bill_data['receipts_time'] = receipts_time
                    #         bill_data['point'] = ordergoods.point
                    #         bill_data['amount'] = ordergoods.price
                    #         bill_data['bill_type'] = order.order_species
                    #         bill_data['payable_amount'] = ordergoods.price + Decimal(int(ordergoods.point) / 100)
                    #         bill, create = MerchantBill.objects.get_or_create(defaults=bill_data,
                    #                                                           receipts_time=receipts_time,
                    #                                                           merchant_id=ordergoods.merchant_id, bill_type=order.order_species)
                    #     else:
                    #         bill.point = bill.point + ordergoods.point
                    #         bill.amount = bill.amount + ordergoods.price
                    #         bill.payable_amount = bill.payable_amount + Decimal(int(ordergoods.point) / 100) + ordergoods.price
                    #         bill.save()
                    #     order.payable_settled_amount = order.payable_settled_amount + Decimal(int(ordergoods.point) / 100) + ordergoods.price
                    #     order.bill_id = bill.id
                    #     order.save()
                    # context = context[:-1] + '(支付宝)'
                    # if order.payable_settled_amount:
                    #     body = {
                    #         "shop_id": order.merchant.ruiyinxinMerchantID,
                    #         "shop_order_id": order.order_id,
                    #         "source": "alipay",
                    #         "money": str(order.payable_settled_amount),
                    #         "context": context
                    #     }
                    #     result = ryx_settle_order(body)
                    #     if result['result_code'] == 'success':
                    #         order.bill_order_id = result['order_id']
                    #         order.save()
                    #     else:
                    #         order.bill_error_msg = result['error_msg']
                    #         order.save()
                    if order.is_profit_sharing == 1:
                        out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                        body = {
                            "program_id": "202316837141378884",
                            "shop_id": order.merchant.ruiyinxinMerchantID,
                            "order_id": out_trade_no,
                            "out_trade_no": order.orderNum,
                            "is_profit": "0"
                        }
                        result = ryx_profitsharing_order(body)
                        profitorder = OrderProfitSharing.objects.filter(order_id=order.id).first()
                        if not profitorder:
                            profitorder, create = OrderProfitSharing.objects.get_or_create(defaults={'order_id': order.id, "out_trade_no": out_trade_no}, order_id=order.id)
                        if result['result_code'] == 'success':
                            order.is_profit_sharing = 2
                            order.save()
                            profitorder.profit_order_id = result['profit_order_id']
                            profitorder.profit_time = datetime.datetime.now()
                            profitorder.save()
                            OrderAdvance.objects.create(
                                order_id=order.id,
                                status=5,
                                remark='商户自行核销订单,解冻资金',
                                merchantuser_id=user.id
                            )
                            receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                            bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species).first()
                            if not bill:
                                bill_data = {}
                                bill_data['merchant_id'] = order.merchant_id
                                bill_data['receipts_time'] = receipts_time
                                bill_data['amount'] = order.total_price
                                bill_data['commission'] = order.freight
                                bill_data['level_id'] = order.merchant.level_id
                                bill_data['payable_amount'] = order.total_price - order.freight
                                bill_data['channel_id'] = 3
                                bill_data['bill_type'] = order.order_species
                                bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species)
                            else:
                                bill.amount = bill.amount + order.total_price
                                bill.commission = bill.commission + order.freight
                                bill.payable_amount = bill.payable_amount + order.total_price - order.freight
                                bill.save()
                            order.payable_settled_amount = order.total_price - order.freight
                            order.bill_id = bill.id
                            order.save()
                        else:
                            order.is_profit_sharing = 2
                            order.save()
                            profitorder.error_msg = result['error_msg']
                            profitorder.profit_status = 2
                            profitorder.save()
                            OrderAdvance.objects.create(
                                order_id=order.id,
                                status=4,
                                remark='商户自行核销订单,解冻资金出错',
                                merchantuser_id=user.id
                            )
                    elif order.is_profit_sharing == 3:
                        out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                        body = {
                            "program_id": "202316837141378884",
                            "shop_id": order.merchant.ruiyinxinMerchantID,
                            "order_id": out_trade_no,
                            "out_trade_no": order.orderNum,
                            "is_profit": "2"
                        }
                        result = ryx_profitsharing_order(body)
                        profitorder = OrderProfitSharing.objects.filter(order_id=order.id).first()
                        if not profitorder:
                            profitorder, create = OrderProfitSharing.objects.get_or_create(defaults={'order_id': order.id, "out_trade_no": out_trade_no}, order_id=order.id)
                        if result['result_code'] == 'success':
                            order.is_profit_sharing = 4
                            order.save()
                            profitorder.profit_order_id = result['profit_order_id']
                            profitorder.profit_time = datetime.datetime.now()
                            profitorder.save()
                            OrderAdvance.objects.create(
                                order_id=order.id,
                                status=5,
                                remark='商户自行核销订单,解冻资金',
                                merchantuser_id=user.id
                            )
                            receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                            bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species).first()
                            if not bill:
                                bill_data = {}
                                bill_data['merchant_id'] = order.merchant_id
                                bill_data['receipts_time'] = receipts_time
                                bill_data['amount'] = order.total_price
                                bill_data['commission'] = order.freight
                                bill_data['level_id'] = order.merchant.level_id
                                bill_data['payable_amount'] = order.total_price - order.freight
                                bill_data['channel_id'] = 3
                                bill_data['bill_type'] = order.order_species
                                bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species)
                            else:
                                bill.amount = bill.amount + order.total_price
                                bill.commission = bill.commission + order.freight
                                bill.payable_amount = bill.payable_amount + order.total_price - order.freight
                                bill.save()
                            order.payable_settled_amount = order.total_price - order.freight
                            order.bill_id = bill.id
                            order.save()
                        else:
                            order.is_profit_sharing = 4
                            order.save()
                            profitorder.error_msg = result['error_msg']
                            profitorder.profit_status = 2
                            profitorder.save()
                            OrderAdvance.objects.create(
                                order_id=order.id,
                                status=4,
                                remark='商户自行核销订单,解冻资金出错',
                                merchantuser_id=user.id
                            )
                except Exception as e:
                    logger.error(e)
                    OrderAdvance.objects.create(
                        order_id=order.id,
                        status=4,
                        remark=f'商户自行核销订单,解冻资金出错,微邮付接口{result}',
                        merchantuser_id=user.id
                    )
        coupon_arr = []
        coupon_list = []
        for goodscoupons in goodscoupons_set:
            coupon_arr.append(goodscoupons.coupons_id)
            coupon_list.append({
                'goods_name': goodscoupons.goods.name,
                'price': goodscoupons.goods.price,
                'count': 1
            })
        data['request_date'] = {'coupon_arr': coupon_arr, 'order_id': order.id}
        data['coupon_list'] = coupon_list
        return Response(data, status=status.HTTP_200_OK)

    def add_express(self, request, *args, **kwargs):
        user = self.request.iser
        express_array = self.request.data.get('express_array', None)
        order_id = self.request.data.get('order_id', None)
        if not all([express_array, order_id]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = self.get_queryset().get(id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.state not in [6, 9]:
            return Response({'error': '订单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                for express in express_array:
                    try:
                        ExpressType.objects.get(id=express['express_type_id'])
                    except:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '无效快递类型'}, status=status.HTTP_400_BAD_REQUEST)
                    express_data = {}
                    express_data['express_type_id'] = express['express_type_id']
                    express_data['express_number'] = express['express_number']
                    express, create = Express.objects.get_or_create(defaults=express_data, express_number=express['express_number'])
                    relevance_data = {}
                    relevance_data['order_id'] = instance.id
                    relevance_data['express_id'] = express.id
                    ExpressOrderRelevance.objects.get_or_create(defaults=relevance_data, order_id=relevance_data['order_id'], express_id=relevance_data['express_id'])
                instance.state = 6
                instance.save()
                OrderAdvance.objects.create(
                    order_id=instance.id,
                    status=3,
                    remark='添加快递单号',
                    merchantuser_id=user.id
                )
                try:
                    express_send.delay({'id': instance.id, 'express_id': express.id})
                except:
                    pass
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '操作失败'}, status=status.HTTP_400_BAD_REQUEST)
            transaction.savepoint_commit(save_id)
            return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def delete_express(self,request):
        user = self.request.iser
        express_id = self.request.data.get('express_id', None)
        order_id = self.request.data.get('order_id', None)
        if not all([order_id, express_id]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = self.get_queryset().get(id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        check_advance_count = OrderAdvance.objects.filter(order_id=instance.id, merchantuser_id=user.id, remark='解绑快递单号').count()
        if check_advance_count >= 3:
            return Response({'error': '解绑失败,超过最大解绑次数'}, status=status.HTTP_400_BAD_REQUEST)
        delete_instance = ExpressOrderRelevance.objects.filter(order_id=order_id, express_id=express_id)
        if not delete_instance:
            return Response({'error': '解绑失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        delete_instance.delete()
        check_relevance = ExpressOrderRelevance.objects.filter(order_id=order_id)
        if not check_relevance:
            instance.state = 9
            instance.save()
        OrderAdvance.objects.create(
            order_id=instance.id,
            status=3,
            remark='解绑快递单号',
            merchantuser_id=user.id
        )
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class MerchantModelViewSet(ModelViewSet):

    pagination_class = MyPage

    def get_queryset(self):
        user = self.request.iser
        queryset = Merchant.objects.filter(merchantuser_id=user.id)
        return queryset

    def get_object(self):
        business_no = self.kwargs['pk']
        if not business_no.isdigit() and len(business_no) != 10:
            raise serializers.ValidationError({'error': '商户id格式有误'})
        instance = self.get_queryset().filter(Q(wyfMerchantID=business_no)).first()
        if instance:
            return instance
        else:
            instance = Merchant.objects.filter(wyfMerchantID=business_no)
            if instance:
                raise serializers.ValidationError({'error': f'当前登录用户信息与商户{business_no}信息不匹配,请联系管理员修改'})
            md5 = hashlib.md5()  # 使用MD5加密模式
            md5.update(str(business_no).encode('utf-8'))  # 将参数字符串传入
            sign = md5.hexdigest()  # 完成加密并转为大写
            url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
            body = {
                'account': 'gdyouzheng',
                'shopId': sign
            }
            reaponse = requests.post(url=url, data=body)
            try:
                reaponse = reaponse.json()
            except:
                raise serializers.ValidationError({'error': '商户id格式有误'})
            if 'wx_channel_merchant_id' not in reaponse:
                raise serializers.ValidationError({'error': '商户id格式有误'})
            if reaponse['wx_channel_merchant_id'] == '':
                raise serializers.ValidationError({'error': '商户id格式有误'})
            with transaction.atomic():
                # 创建事务保存点
                save_id = transaction.savepoint()
                try:
                    merchant_data = {}
                    channel_mch_id = reaponse['channel_mch_id']
                    channel = Channel.objects.filter(mchid=channel_mch_id).first()
                    if channel:
                        merchant_data['channel_id'] = channel.id
                    merchant_data['name'] = reaponse['shopName']
                    merchant_data['short_name'] = reaponse['shopNickname']
                    merchant_data['wyfMerchantID'] = business_no
                    merchant_data['ruiyinxinMerchantID'] = sign
                    merchant_data['create_time'] = datetime.datetime.now()
                    if reaponse['businessType'] == '1':
                        merchant_data['subject_type'] = 3
                    elif reaponse['businessType'] == '2':
                        merchant_data['subject_type'] = 2
                    elif reaponse['businessType'] == '3':
                        merchant_data['subject_type'] = 1
                    else:
                        merchant_data['subject_type'] = 4
                    level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                    if level:
                        merchant_data['level_id'] = level.id
                    merchantuser = self.request.iser
                    if merchantuser:
                        merchant_data['merchantuser_id'] = merchantuser.id
                    merchant_data['account_name'] = reaponse['cardName']
                    merchant_data['account_bank'] = reaponse['bankName']
                    merchant_data['account_number'] = reaponse['card']
                    card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                    card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png', key=card_copy)
                    if card_copy_url:
                        merchant_data['card_copy'] = card_copy
                    merchant_data['identification_number'] = reaponse['identity']
                    merchant_data['store_address'] = reaponse['address']
                    store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                    store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                    if store_header_copy_url:
                        merchant_data['store_header_copy'] = store_header_copy
                    merchant, cereate = Merchant.objects.update_or_create(defaults=merchant_data, wyfMerchantID=business_no)
                    if not merchant.managerName:
                        merchant.managerName = reaponse['keeper']
                    if not merchant.managermobile:
                        merchant.managermobile = reaponse['phone']
                    if not merchant.prov_name:
                        merchant.prov_name = reaponse['province']
                        merchant.city_name = reaponse['city']
                        merchant.district_name = reaponse['area']
                    if not merchant.business_category:
                        merchant.business_category_id = 1
                    merchant.save()
                    if cereate and merchant.channel:
                        store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                        if store_header_copy_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                        store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        store_indoor_copy_url = sync_img_to_local(
                            f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                        if store_indoor_copy_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                        merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                        merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                        if merchantCheck_url:
                            MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                    merchantchannel_data = {
                        'merchant_id': merchant.id
                    }
                    if reaponse['allchannelJson']['channel_ruiyinxin']:
                        if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
                            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
                            merchantchannel_data['channel_id'] = 2
                            merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
                            MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                  merchant_id=merchant.id,
                                                                  channel_id=merchantchannel_data['channel_id'])
                    if reaponse['allchannelJson']['channel_sxf_tq']:
                        if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                            merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                            merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_no']
                            merchantchannel_data['channel_id'] = 3
                            merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_3']
                            MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                  merchant_id=merchant.id,
                                                                  channel_id=merchantchannel_data['channel_id'])
                    transaction.savepoint_commit(save_id)
                except Exception as e:
                    logger.error(e)
                    transaction.savepoint_rollback(save_id)
                    raise serializers.ValidationError({'error': '商户id格式有误'})
                return merchant

    def get_serializer_class(self):
        return MerchantModelSerializer

    def add_image(self, request):
        user = self.request.iser
        img = self.request.FILES.get('img', None)
        business_no = self.request.data.get('business_no', None)
        if not all([img, business_no]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if img.size > 2097152:
            return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = img.read()
        img.seek(0)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            img_id = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
            mid_img = pic_upload(img_str, key=img_id)
        except Exception as e:
            logger.error(e)
            return Response({'error': '图片上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        instance = MerchantImage.objects.create(merchant_id=merchant.id, image=img_id)
        data = MerchantImageSerializer(instance).data
        return Response({'success': '操作成功', 'img': data}, status=status.HTTP_200_OK)

    def delete_image(self, request):
        user = self.request.iser
        img_id = self.request.data.get('img_id', None)
        instance = MerchantImage.objects.filter(merchant__merchantuser_id=user.id, id=img_id).first()
        try:
            old_store_logo_copy = instance.image
            pic_delete(old_store_logo_copy)
        except:
            pass
        instance.delete()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def update_logo(self, request):
        user = self.request.iser
        img = self.request.FILES.get('img', None)
        business_no = self.request.data.get('business_no', None)
        if not all([img, business_no]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if img.size > 2097152:
            return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = img.read()
        img.seek(0)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            img_id = f'youhuiquanyi/{business_no}/store_logo_copy{"%06d" % randint(0, 999999)}.png'
            mid_img = pic_upload(img_str, key=img_id)
        except Exception as e:
            logger.error(e)
            return Response({'error': '图片上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            old_store_logo_copy = merchant.store_logo_copy
            pic_delete(old_store_logo_copy)
        except:
            pass
        merchant.store_logo_copy = img_id
        merchant.save()
        merchant = Merchant.objects.get(id=merchant.id)
        return Response({'success': '操作成功', 'store_logo_copy': merchant.store_logo_copy.url}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        is_online = self.request.data.get('is_online', None)
        business_category_id = self.request.data.get('business_category_id', None)
        open_work_time = self.request.data.get('open_work_time', None)
        close_work_time = self.request.data.get('close_work_time', None)
        managerName = self.request.data.get('managerName', None)
        prov_name = self.request.data.get('prov_name', None)
        city_name = self.request.data.get('city_name', None)
        district_name = self.request.data.get('district_name', None)
        longitude = self.request.data.get('longitude', None)
        latitude = self.request.data.get('latitude', None)
        store_address = self.request.data.get('store_address', None)
        merchant_desc = self.request.data.get('merchant_desc', None)
        short_name = self.request.data.get('short_name', None)
        provincial_code = self.request.data.get('provincial_code', None)
        region = self.request.data.get('region', None)
        if business_category_id:
            try:
                business_category = MerchantBusinessCategory.objects.get(id=business_category_id)
            except:
                return Response({'error': '无效经营类目'}, status=status.HTTP_400_BAD_REQUEST)
            instance.business_category_id = business_category_id
        if open_work_time:
            try:
                time.strptime(str(open_work_time), "%H:%M")
            except:
                return Response({'error': '经营时间参数有误!'}, status=status.HTTP_400_BAD_REQUEST)
            busStartTm = f'1900-01-01 {open_work_time}:00'
            instance.open_work_time = busStartTm
        if close_work_time:
            try:
                time.strptime(str(close_work_time), "%H:%M")
            except:
                return Response({'error': '经营时间参数有误!'}, status=status.HTTP_400_BAD_REQUEST)
            busEndTm = f'1900-01-01 {close_work_time}:00'
            instance.close_work_time = busEndTm
        if managerName:
            instance.managerName = managerName
        if merchant_desc:
            instance.merchant_desc = merchant_desc
        if short_name:
            instance.short_name = short_name
        if prov_name:
            instance.prov_name = prov_name
        if city_name:
            instance.city_name = city_name
        if district_name:
            instance.district_name = district_name
        if store_address:
            instance.store_address = store_address
        if longitude:
            instance.longitude = longitude
        if latitude:
            instance.latitude = latitude
        if region:
            if type(region) != type([]) and len(region) != 3:
                return Response({'error': '省市区数据格式有误'}, status=status.HTTP_400_BAD_REQUEST)
            instance.prov_name = region[0]
            instance.city_name = region[1]
            instance.district_name = region[2]
        if provincial_code:
            if type(provincial_code) != type([]) and len(provincial_code) != 3:
                return Response({'error': '省市区编码数据格式有误'}, status=status.HTTP_400_BAD_REQUEST)
            instance.prov_code = provincial_code[0]
            instance.city_code = provincial_code[1]
            instance.district_code = provincial_code[2]
        if is_online:
            if str(is_online) not in ['2', '3']:
                return Response({'error': '是否上架参数有误'}, status=status.HTTP_400_BAD_REQUEST)
            instance.is_online = is_online
        try:
            instance.save()
            return Response({'success': '操作成功'}, status=status.HTTP_200_OK)
        except:
            return Response({'error': '提交邮惠权益数据失败,如有疑问请联系客服!'}, status=status.HTTP_400_BAD_REQUEST)

    def get_address(self, request):
        latitude = self.request.query_params.get('latitude', None)
        longitude = self.request.query_params.get('longitude', None)
        if not all([latitude, longitude]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            url = 'http://api.map.baidu.com/geocoder/v2/?location=' + latitude + ',' + longitude + '&output=json&pois=1&ak=GShg48h4U0XOZnd7vGa03AdfoKKGT3v5'
            dictjson = {}  # 声明一个字典
            # get()获取json里面的数据
            jsonResult = requests.get(url=url).json()['result']
            address = jsonResult.get('addressComponent')
            # 国家
            country = address.get('country')
            # 国家编号（0：中国）
            country_code = address.get('country_code')
            # 省
            province = address.get('province')
            # 城市
            city = address.get('city')
            # 城市等级
            city_level = address.get('city_level')
            # 县级
            district = address.get('district')
            # 把获取到的值，添加到字典里（添加）
            dictjson['country'] = country
            dictjson['country_code'] = country_code
            dictjson['province'] = province
            dictjson['city'] = city
            dictjson['city_level'] = city_level
            dictjson['district'] = district
            provincial_code = []
            try:
                city = AreaCode.objects.filter(district=city).first()
                district = AreaCode.objects.filter(district=district).first()
                if city and district:
                    provincial_code.append(city.province_code)
                    provincial_code.append(city.code)
                    provincial_code.append(district.code)
            except:
                pass
            dictjson['provincial_code'] = provincial_code
            return Response(dictjson, status=status.HTTP_200_OK)
        except:
            return Response({'error': '解析出错'}, status=status.HTTP_400_BAD_REQUEST)

    def sms_codes(self, request):
        mobile = self.request.query_params.get('mobile', None)
        if not mobile:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
        redis_conn = get_redis_connection("verify_code")
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        content = f'【微邮付】登录验证码为：{sms_code}，若非本人操作，请忽略。'
        result = common_msg(mobile, content)
        return Response({"errmsg": "发送短信验证码成功"}, status=status.HTTP_200_OK)

    def update_mobile(self, request):
        id = self.request.data.get('id', None)
        sms_code = self.request.data.get('sms_code', None)
        managermobile = self.request.data.get('mobile', None)
        if not all([id, sms_code, managermobile]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        redis_conn = get_redis_connection("verify_code")
        sms_code_server = redis_conn.get("sms_%s" % managermobile)
        if sms_code_server is None:
            return Response({'error': "短信验证码失效"}, status=status.HTTP_400_BAD_REQUEST)
        sms_code_server = sms_code_server.decode()
        if sms_code_server != str(sms_code):
            return Response({'error': "输入验证码有误"}, status=status.HTTP_400_BAD_REQUEST)
        redis_conn.delete("sms_%s" % managermobile)
        try:
            instance = self.get_queryset().get(Q(id=id) | Q(wyfMerchantID=id))
        except:
            return Response({'error': '无效商户id'}, status=status.HTTP_400_BAD_REQUEST)
        instance.managermobile = managermobile
        instance.save()
        return Response({'success': '修改手机号成功'}, status=status.HTTP_200_OK)

    def verify_order(self, request):
        user = self.request.iser
        if user.is_psbc_card != 0:
            return Response({'error': '您已经完成绑定,无需重复操作'}, status=status.HTTP_400_BAD_REQUEST)
        bindcardorder = MerchantBindCardOrder.objects.filter(merchantuser_id=user.id, order_status=1).first()
        if not bindcardorder:
            out_trade_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            out_refund_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            bindcardorder_data = {}
            bindcardorder_data['merchantuser_id'] = user.id
            bindcardorder_data['amount'] = 0.01
            bindcardorder_data['order_status'] = 1
            bindcardorder_data['description'] = '邮政一分钱验卡活动'
            bindcardorder_data['out_trade_no'] = out_trade_no
            bindcardorder_data['out_refund_no'] = out_refund_no
            bindcardorder, create = MerchantBindCardOrder.objects.get_or_create(defaults=bindcardorder_data, merchantuser_id=user.id, order_status=1)
        else:
            today = datetime.datetime.now() - datetime.timedelta(hours=2)
            if bindcardorder.create_time < today:
                bindcardorder.order_status = 3
                bindcardorder.save()
                out_trade_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                out_refund_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                bindcardorder_data = {}
                bindcardorder_data['merchantuser_id'] = user.id
                bindcardorder_data['amount'] = 0.01
                bindcardorder_data['order_status'] = 1
                bindcardorder_data['description'] = '邮政一分钱验卡活动'
                bindcardorder_data['out_trade_no'] = out_trade_no
                bindcardorder_data['out_refund_no'] = out_refund_no
                bindcardorder, create = MerchantBindCardOrder.objects.get_or_create(defaults=bindcardorder_data, merchantuser_id=user.id, order_status=1)
        data = MerchantBindCardOrderRetrieveModelSerializer(bindcardorder).data
        return Response(data, status=status.HTTP_200_OK)

    def payment(self, request):
        user = self.request.iser
        order_id = self.request.query_params.get('order_id', None)
        if not order_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = MerchantBindCardOrder.objects.get(merchantuser_id=user.id, id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if bindcardorder.order_status != 1:
            return Response({'error': '订单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        openid = user.openid
        amount = 1
        appid = 'wxbf07fc5376ab43a2'
        data_json = {}
        data_json['appid'] = appid
        data_json['mchid'] = '1486198522'
        data_json['description'] = bindcardorder.description
        data_json['out_trade_no'] = bindcardorder.out_trade_no
        data_json['notify_url'] = 'https://api.sutpay.com/cpay/merchant_wxpay_result/'
        data_json['amount'] = {"total": amount}
        data_json['payer'] = {"openid": openid}
        data_dict = pay_transactions_jsapi(data_json, appid)
        # data_dict = pay_transactions_native(data_json)
        if 'code' in data_dict:
            return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
        data_dict['out_trade_no'] = bindcardorder.out_trade_no
        return Response(data_dict, status=status.HTTP_200_OK)

    def big_turntable(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '请上传商户id'}, status=status.HTTP_400_BAD_REQUEST)
        merchant = Merchant.objects.filter(merchantuser_id=user.id, wyfMerchantID=business_no).first()
        if not merchant:
            return Response({'error': '无效商户id'}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.level.district_id == 9897:
            data_now = datetime.datetime.now()
            available_begin_time_str = '2023-12-12 09:00:00'
            available_end_time_str = '2023-12-31 23:59:59'
            available_begin_time = datetime.datetime.strptime(available_begin_time_str, '%Y-%m-%d %H:%M:%S')
            available_end_time = datetime.datetime.strptime(available_end_time_str, '%Y-%m-%d %H:%M:%S')
            if data_now > available_end_time:
                activity_status = 2
                c_time = available_end_time_str
            else:
                if data_now < available_begin_time:
                    activity_status = 1
                    c_time = available_begin_time_str
                else:
                    activity_status = 3
                    c_time = available_end_time_str
            white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id=3)
            if not white_table:
                count = 0
                total_count = 0
                # return Response({'error': '该活动仅限汕尾城区达标商户参加'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=3).count()
                total_count = 1 - check_draw
                account = f'{data_now.strftime("%Y%m%d")}{business_no}'
                if total_count <= 0:
                    count = 0
                else:
                    check_draw_today = MerchantEightEightDraw.objects.filter(account=account)
                    if check_draw_today:
                        count = 0
                    else:
                        count = 1
            data = {}
            lists = [
                {"id": 9, "msg": "鼓励金13.88元", "type": "1", 'amount': '13.88'},
                {"id": 7, "msg": "鼓励金38.88元", "type": "1", 'amount': '38.88'},
                {"id": 6, "msg": "谢谢参与", "type": "1", 'amount': '0'},
                {"id": 4, "msg": "鼓励金88.88元", "type": "1", 'amount': '88.88'},
                {"id": 8, "msg": "鼓励金188.88元", "type": "1", 'amount': '188.88'},
                {"id": 13, "msg": "谢谢参与", "type": "0", 'amount': '0'}
            ]
            data['lists'] = lists
            data['activity_description'] = '''活动对象：仅限广东汕尾城区微邮付商户参与抽奖
活动时间：2023年12月1日 09:00:00 至 2023 年12月 31日 23:59:59
参与规则：2023年12月当月微邮付有效交易笔数达 8 笔，且每笔≥2 元的商户即可参与抽奖。每个商户仅有一次抽奖机会，100%中奖。当天的交易需要第二天13点后才可以抽奖，例如商户在12月15日完成了该任务，则12月16日13点后才可以抽奖。
活动奖品：1.88元,10.88元,88.88元,188.88元,388.88元支付宝权益金
抽奖方法：当用户完成当月微邮付有效交易笔数达 8 笔，且每笔≥2 元后会有一次免费抽奖机会，点击圆盘【达标抽奖】按钮，显示中奖后，填写支付宝账户与支付宝认证信息即可领奖，奖项在24小时内派发完成。'''
            data['description'] = '''活动对象：仅限广东汕尾城区微邮付商户参与抽奖
活动时间：2023年12月1日 09:00:00 至 2023 年12月 31日 23:59:59
参与规则：2023年12月当月微邮付有效交易笔数达 8 笔，且每笔≥2 元的商户即可参与抽奖。每个商户仅有一次抽奖机会，100%中奖。当天的交易需要第二天13点后才可以抽奖，例如商户在12月15日完成了该任务，则12月16日13点后才可以抽奖。
活动奖品：1.88元,10.88元,88.88元,188.88元,388.88元支付宝权益金
抽奖方法：当用户完成当月微邮付有效交易笔数达 8 笔，且每笔≥2 元后会有一次免费抽奖机会，点击圆盘【达标抽奖】按钮，显示中奖后，填写支付宝账户与支付宝认证信息即可领奖，奖项在24小时内派发完成。'''
            data['count'] = count
            data['total_count'] = total_count
            data['activity_status'] = activity_status
            data['c_time'] = c_time
            data['activity_id'] = 3
            return Response(data, status=status.HTTP_200_OK)
        else:
            data_now = datetime.datetime.now()
            check_activity = MerchantEightEightActivity.objects.filter(activity_start_time__lte=data_now, activity_end_time__gte=data_now, activity_type=1).exclude(activity_id=3).first()
            if check_activity:
                draw_end_time = check_activity.draw_end_time
                available_end_time = check_activity.activity_end_time
                activity_id = check_activity.activity_id
                activity_status = 3
                c_time = available_end_time.strftime('%Y-%m-%d %H:%M:%S')
                white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id=activity_id)
                if not white_table:
                    return Response({'error': '该活动仅限深圳达标商户参加'}, status=status.HTTP_400_BAD_REQUEST)
                check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=activity_id).count()
                total_count = 1 - check_draw
                account = f'{data_now.strftime("%Y%m%d")}{business_no}'
                if draw_end_time < data_now:
                    count = 0
                else:
                    if total_count <= 0:
                        count = 0
                    else:
                        check_draw_today = MerchantEightEightDraw.objects.filter(account=account)
                        if check_draw_today:
                            count = 0
                        else:
                            count = 1
                data = {}
                activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id)
                lists = []
                for activity_prize in activity_prize_set:
                    lists.append({
                        'id': activity_prize.id,
                        'msg': activity_prize.prize_name,
                        'type': activity_prize.prize_type,
                        'amount': activity_prize.amount
                    })
                # lists = [
                #     {"id": 9, "msg": "鼓励金13.88元", "type": "1", 'amount': '13.88'},
                #     {"id": 7, "msg": "鼓励金38.88元", "type": "1", 'amount': '38.88'},
                #     {"id": 6, "msg": "谢谢参与", "type": "0", 'amount': '0'},
                #     {"id": 4, "msg": "鼓励金88.88元", "type": "1", 'amount': '88.88'},
                #     {"id": 8, "msg": "鼓励金188.88元", "type": "1", 'amount': '188.88'},
                #     {"id": 13, "msg": "谢谢参与", "type": "0", 'amount': '0'}
                # ]
                data['lists'] = lists
                data['activity_description'] = check_activity.activity_description
                data['description'] = check_activity.activity_description
                data['count'] = count
                data['total_count'] = total_count
                data['activity_status'] = activity_status
                data['c_time'] = c_time
                data['activity_id'] = 5
                return Response(data, status=status.HTTP_200_OK)
            else:
                return Response({'error': '该活动仅限深圳达标商户参加'}, status=status.HTTP_400_BAD_REQUEST)

    def lucky_draw(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        merchant = Merchant.objects.filter(merchantuser_id=user.id, wyfMerchantID=business_no).first()
        if not merchant:
            return Response({'error': '无效商户id'}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.level.district_id == 9897:
            data_now = datetime.datetime.now()
            available_begin_time_str = '2023-12-12 09:00:00'
            available_end_time_str = '2023-12-31 23:59:59'
            available_begin_time = datetime.datetime.strptime(available_begin_time_str, '%Y-%m-%d %H:%M:%S')
            available_end_time = datetime.datetime.strptime(available_end_time_str, '%Y-%m-%d %H:%M:%S')
            if data_now > available_end_time:
                return Response({'error': '活动已结束,感谢支持'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if data_now < available_begin_time:
                    return Response({'error': '活动尚未开始,敬请等待'}, status=status.HTTP_400_BAD_REQUEST)
            white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id=3).first()
            if not white_table:
                return Response({'error': '您没有达标,请使用微邮付码牌进行交易,达标后次日即可获得抽奖'}, status=status.HTTP_400_BAD_REQUEST)
            check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=3).count()
            total_count = 1 - check_draw
            account = f'{data_now.strftime("%Y%m%d")}{business_no}'
            if total_count <= 0:
                return Response({'error': '抽奖次数已消耗完,感谢支持'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                check_draw_today = MerchantEightEightDraw.objects.filter(account=account)
                if check_draw_today:
                    return Response({'error': '今日抽奖次数已消耗完,明日再来'}, status=status.HTTP_400_BAD_REQUEST)
            draw_list = []
            if white_table.is_win_type == 1:
                draw_list.append(white_table.win_type)
            else:
                draw_counts = MerchantEightEightDraw.objects.filter(activity_id=2).values('win_type').annotate(Count('win_type'))
                draw_count_dict = {}
                for draw_count in draw_counts:
                    draw_count_dict[draw_count['win_type']] = draw_count['win_type__count']
                limit_count = {
                    1: 5903,
                    2: 700,
                    3: 290,
                    7: 100
                }
                for key, value in limit_count.items():
                    if key in draw_count_dict:
                        if value > draw_count_dict[key]:
                            draw_list.append(key)
                    else:
                        draw_list.append(key)
            shuffle(draw_list)
            win_type = draw_list[0]
            out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            draw_data = {}
            draw_data['merchantuser_id'] = user.id
            draw_data['state'] = 1
            draw_data['desc'] = '微邮付商户节达标回馈'
            draw_data['amount'] = MerchantEightEightDraw.AMOUNT_ENUM[win_type]
            draw_data['partner_trade_no'] = out_biz_no
            draw_data['win_type'] = win_type
            draw_data['business_no'] = business_no
            draw_data['account'] = account
            draw_data['level_id'] = merchant.level_id
            draw_data['activity_id'] = 3
            draw_data['expired_time'] = available_end_time_str
            instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
            data = {}
            data["id"] = win_type
            data["take_id"] = instance.id
            data["amount"] = instance.amount
            data["activity_name"] = ''
            data["msg"] = ''
            data["available_time"] = ''
            data["win_type_str"] = instance.get_win_type_display()
            data["win_type"] = instance.win_type
            try:
                check_activity = MerchantEightEightActivity.objects.get(activity_id=3)
                check_activity.total_count += 1
                check_activity.save()
            except:
                pass
            return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
        else:
            if user.is_psbc_card == 0:
                return Response({'error': '请先完成验卡操作'}, status=status.HTTP_400_BAD_REQUEST)
            data_now = datetime.datetime.now()
            check_activity = MerchantEightEightActivity.objects.exclude(activity_id=3).filter(activity_start_time__lte=data_now, activity_end_time__gte=data_now, activity_type=1).first()
            if check_activity:
                draw_end_time = check_activity.draw_end_time
                available_end_time = check_activity.activity_end_time
                activity_id = check_activity.activity_id
                # available_begin_time_str = '2023-09-28 09:00:00'
                # available_end_time_str = '2023-10-08 23:59:59'
                # available_begin_time = datetime.datetime.strptime(available_begin_time_str, '%Y-%m-%d %H:%M:%S')
                # available_end_time = datetime.datetime.strptime(available_end_time_str, '%Y-%m-%d %H:%M:%S')
                # if data_now > available_end_time:
                #     return Response({'error': '活动已结束,感谢支持'}, status=status.HTTP_400_BAD_REQUEST)
                # else:
                #     if data_now < available_begin_time:
                #         return Response({'error': '活动尚未开始,敬请等待'}, status=status.HTTP_400_BAD_REQUEST)
                #     else:
                #         publish_start_time = datetime.datetime.strptime(data_now.strftime('%Y-%m-%d 09:00:00'), '%Y-%m-%d %H:%M:%S')
                #         if data_now < publish_start_time:
                #             return Response({'error': '不是活动进行时间,请等待'}, status=status.HTTP_400_BAD_REQUEST)
                if draw_end_time < data_now:
                    return Response({'error': '已过活动抽奖时间,请下期继续参与,多谢支持'}, status=status.HTTP_400_BAD_REQUEST)
                white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id=activity_id).first()
                if not white_table:
                    return Response({'error': '该活动仅限深圳达标商户参加'}, status=status.HTTP_400_BAD_REQUEST)
                check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=activity_id).count()
                total_count = 1 - check_draw
                account = f'{data_now.strftime("%Y%m%d")}{business_no}'
                if total_count <= 0:
                    return Response({'error': '抽奖次数已消耗完,感谢支持'}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    check_draw_today = MerchantEightEightDraw.objects.filter(account=account)
                    if check_draw_today:
                        return Response({'error': '今日抽奖次数已消耗完,明日再来'}, status=status.HTTP_400_BAD_REQUEST)
                draw_list = []
                if white_table.is_win_type == 1:
                    draw_list.append(white_table.win_type)
                else:
                    draw_counts = MerchantEightEightDraw.objects.filter(activity_id=check_activity.id).values('win_type').annotate(Count('win_type'))
                    draw_count_dict = {}
                    for draw_count in draw_counts:
                        draw_count_dict[draw_count['win_type']] = draw_count['win_type__count']
                    activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, prize_type=1)
                    limit_count = {}
                    for activity_prize in activity_prize_set:
                        limit_count[activity_prize.id] = activity_prize.count
                    # limit_count = {
                    #     9: 1489,
                    #     7: 100,
                    #     4: 5,
                    #     8: 1
                    # }
                    # limit_count = {
                    #     9: 1,
                    #     7: 0,
                    #     4: 0,
                    #     8: 0
                    # }
                    for key, value in limit_count.items():
                        if key in draw_count_dict:
                            if value > draw_count_dict[key]:
                                draw_list.append(key)
                        else:
                            if value > 0:
                                draw_list.append(key)
                if draw_list:
                    shuffle(draw_list)
                    win_type = draw_list[0]
                    out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                    draw_data = {}
                    draw_data['merchantuser_id'] = user.id
                    draw_data['state'] = 1
                    draw_data['desc'] = '微邮付商户节达标回馈'
                    draw_data['amount'] = MerchantEightEightActivityPrize.objects.get(id=win_type).amount
                    draw_data['partner_trade_no'] = out_biz_no
                    draw_data['win_type'] = win_type
                    draw_data['business_no'] = business_no
                    draw_data['account'] = account
                    draw_data['level_id'] = merchant.level_id
                    draw_data['activity_id'] = activity_id
                    draw_data['expired_time'] = available_end_time
                    instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
                    data = {}
                    data["id"] = win_type
                    data["take_id"] = instance.id
                    data["amount"] = instance.amount
                    data["activity_name"] = ''
                    data["msg"] = ''
                    data["available_time"] = ''
                    data["win_type_str"] = instance.get_win_type_display()
                    data["win_type"] = instance.win_type
                else:
                    activity_prize = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, prize_type=0).first()
                    out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                    draw_data = {}
                    draw_data['merchantuser_id'] = user.id
                    draw_data['state'] = 1
                    draw_data['desc'] = '微邮付商户节达标回馈'
                    draw_data['amount'] = 0
                    draw_data['partner_trade_no'] = out_biz_no
                    draw_data['win_type'] = 6
                    draw_data['business_no'] = business_no
                    draw_data['account'] = account
                    draw_data['level_id'] = merchant.level_id
                    draw_data['activity_id'] = activity_id
                    draw_data['expired_time'] = available_end_time
                    instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
                    data = {}
                    data["id"] = activity_prize.id
                    data["take_id"] = instance.id
                    data["amount"] = instance.amount
                    data["activity_name"] = ''
                    data["msg"] = ''
                    data["available_time"] = ''
                    data["win_type_str"] = instance.get_win_type_display()
                    data["win_type"] = instance.win_type
                try:
                    check_activity.total_count += 1
                    check_activity.save()
                except:
                    pass
                return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '该活动仅限深圳达标商户参加'}, status=status.HTTP_400_BAD_REQUEST)

        # is_vip = MerchantEightEightWhiteTable.objects.filter(business_no=business_no)
        # draw_counts = MerchantEightEightDraw.objects.filter(create_time__gte=datetime.datetime.strptime(data_now.strftime('%Y-%m-%d 00:00:00'), '%Y-%m-%d %H:%M:%S'), create_time__lte=datetime.datetime.strptime(data_now.strftime('%Y-%m-%d 23:59:59'), '%Y-%m-%d %H:%M:%S')).exclude(win_type=6).values('win_type').annotate(Count('win_type'))
        # draw_count_dict = {}
        # for draw_count in draw_counts:
        #     draw_count_dict[draw_count['win_type']] = draw_count['win_type__count']
        # start_time1 = datetime.datetime.strptime('2023-08-08 23:59:59', '%Y-%m-%d %H:%M:%S')
        # start_time2 = datetime.datetime.strptime('2023-08-16 23:59:59', '%Y-%m-%d %H:%M:%S')
        # if data_now < start_time1:
        #     limit_count1 = {
        #         1: 13400,
        #         2: 21
        #     }
        #     limit_count2 = {
        #         3: 45,
        #         4: 38,
        #         5: 19
        #     }
        # elif data_now < start_time2:
        #     limit_count1 = {
        #         1: 7800,
        #         2: 9
        #     }
        #     limit_count2 = {
        #         3: 5,
        #         4: 2,
        #         5: 1
        #     }
        # else:
        #     limit_count1 = {
        #         1: 1600,
        #         2: 9
        #     }
        #     limit_count2 = {
        #         3: 5,
        #         4: 2,
        #         5: 1
        #     }
        # draw_list = []
        # if is_vip:
        #     for key, value in limit_count2.items():
        #         if key in draw_count_dict:
        #             if value > draw_count_dict[key]:
        #                 draw_list.append(key)
        #         else:
        #             draw_list.append(key)
        #     if not draw_list:
        #         for key, value in limit_count1.items():
        #             if key in draw_count_dict:
        #                 if value > draw_count_dict[key]:
        #                     draw_list.append(key)
        #             else:
        #                 draw_list.append(key)
        # else:
        #     for key, value in limit_count1.items():
        #         if key in draw_count_dict:
        #             if value > draw_count_dict[key]:
        #                 draw_list.append(key)
        #         else:
        #             draw_list.append(key)
        # data = {}
        # if len(draw_list) == 0:
        #     draw_data = {}
        #     data["id"] = 6
        #     data["take_id"] = ''
        #     data["amount"] = ''
        #     data["activity_name"] = ''
        #     data["msg"] = ''
        #     data["available_time"] = ''
        #     data["win_type_str"] = '谢谢参与'
        #     data["win_type"] = 6
        #     draw_data['merchantuser_id'] = user.id
        #     draw_data['state'] = 2
        #     draw_data['desc'] = '谢谢参与'
        #     draw_data['win_type'] = 6
        #     draw_data['business_no'] = business_no
        #     draw_data['account'] = account
        #     draw_data['level_id'] = merchant.level_id
        #     instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
        #     return Response({'success': '谢谢参与', 'data': data}, status=status.HTTP_200_OK)
        # else:
        #     shuffle(draw_list)
        #     win_type = draw_list[0]
        #     out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        #     draw_data = {}
        #     draw_data['merchantuser_id'] = user.id
        #     draw_data['state'] = 1
        #     draw_data['desc'] = '微邮付88商户节回馈'
        #     draw_data['amount'] = MerchantEightEightDraw.AMOUNT_ENUM[win_type]
        #     draw_data['partner_trade_no'] = out_biz_no
        #     draw_data['win_type'] = win_type
        #     draw_data['business_no'] = business_no
        #     draw_data['account'] = account
        #     draw_data['level_id'] = merchant.level_id
        #     instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
        #     data["id"] = win_type
        #     data["take_id"] = instance.id
        #     data["amount"] = instance.amount
        #     data["activity_name"] = ''
        #     data["msg"] = ''
        #     data["available_time"] = ''
        #     data["win_type_str"] = instance.get_win_type_display()
        #     data["win_type"] = instance.win_type
        #     return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)

    def check_order(self, request):
        user = self.request.iser
        out_trade_no = self.request.query_params.get('out_trade_no', None)
        if not out_trade_no:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            bindcardorder = MerchantBindCardOrder.objects.get(merchantuser_id=user.id, out_trade_no=out_trade_no)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if bindcardorder.bank_type:
            if 'PSBC' in bindcardorder.bank_type:
                return Response({'success': '查询成功', 'status': 1}, status=status.HTTP_200_OK)
            else:
                return Response({'success': '查询成功', 'status': 0}, status=status.HTTP_200_OK)
        else:
            return Response({'success': '查询成功', 'status': 0}, status=status.HTTP_200_OK)

    def apply_admission(self, request):
        user = self.request.iser
        signature_copy = self.request.data.get('signature_copy', None)
        contract = self.request.data.get('contract', None)
        business_no = self.request.data.get('business_no', None)
        if not business_no:
            return Response({'error': '缺少商户号'}, status=status.HTTP_400_BAD_REQUEST)
        if not signature_copy:
            return Response({'error': '缺少手写签名照'}, status=status.HTTP_400_BAD_REQUEST)
        # if not contract:
        #     return Response({'error': '缺少分账协议'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.is_mall in [2, 3]:
            return Response({'error': '商户已入驻商城,无需重复提交'}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.is_mall == 5:
            return Response({'error': '申请单正在审核中,无需重复提交'}, status=status.HTTP_400_BAD_REQUEST)
        apply = MerchantMallApplyment.objects.filter(merchant_id=merchant.id, applyment_state__in=[1, 2, 4, 5], applyment_type=1)
        if apply:
            return Response({'error': '申请单正在审核中'}, status=status.HTTP_400_BAD_REQUEST)
        apply = MerchantMallApplyment.objects.filter(merchant_id=merchant.id, applyment_state=0, applyment_type=1).first()
        if apply:
            apply.signature_copy = signature_copy.replace('https://circle.sutpay.cn', '')
            # apply.contract = contract.replace('https://circle.sutpay.cn', '')
            apply.context = '入驻微邮惠商城申请'
            apply.applyment_state = 1
            apply.save()
        else:
            mall_apply_data = {}
            mall_apply_data['signature_copy'] = signature_copy.replace('https://circle.sutpay.cn', '')
            # mall_apply_data['contract'] = contract.replace('https://circle.sutpay.cn', '')
            mall_apply_data['context'] = '入驻微邮惠商城申请'
            mall_apply_data['merchant_id'] = merchant.id
            mall_apply_data['applyment_state'] = 1
            instance, create = MerchantMallApplyment.objects.get_or_create(defaults=mall_apply_data, merchant_id=merchant.id, applyment_state=1)
        merchant.is_mall = 5
        merchant.applyment_state = 2
        merchant.verify_state = 1
        merchant.save()
        eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
        # task_id = automatic_audit_mall_applyment.apply_async(({"applyment_id": instance.id},), eta=eta)
        return Response({'success': '提交成功'}, status=status.HTTP_200_OK)

    def applyment(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '缺少商户号'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['applyment_type_str'] = ''
        data['applyment_type'] = ''
        data['context'] = ''
        data['create_time'] = ''
        data['applyment_state'] = ''
        data['applyment_state_str'] = ''
        data['contract'] = ''
        data['sign_url'] = ''
        data['reject_reason'] = ''
        if merchant.is_mall == 3:
            data = {}
            data['applyment_type_str'] = '入驻申请单'
            data['applyment_type'] = '1'
            data['context'] = ''
            data['create_time'] = ''
            data['applyment_state'] = '3'
            data['applyment_state_str'] = '封控'
            data['contract'] = ''
            data['sign_url'] = ''
            data['reject_reason'] = '商户状态错误,请联系客服处理'
        else:
            instance = MerchantMallApplyment.objects.filter(applyment_state__in=[1, 3, 2, 4, 5], merchant_id=merchant.id).last()
            if instance:
                data['reject_reason'] = instance.reject_reason
                data['applyment_type_str'] = instance.get_applyment_type_display()
                data['applyment_type'] = instance.applyment_type
                data['context'] = instance.context
                data['create_time'] = instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                if instance.applyment_state == 5:
                    data['applyment_state'] = 1
                    data['applyment_state_str'] = '审核中'
                else:
                    data['applyment_state'] = instance.applyment_state
                    data['applyment_state_str'] = instance.get_applyment_state_display()
            # if instance.applyment_state == 1:
            #     pass
            #     # result = get_sign_contract_url(merchant.ruiyinxinMerchantID)
            #     # if result['result_code'] != 'fail':
            #     #     if result['data']['open_status'] == 2:
            #     #         if not instance.sign_url:
            #     #             signUrl = result['data']['signUrl']
            #     #             sign_url = make_qrcode1(merchant.ruiyinxinMerchantID, signUrl, key=None)
            #     #             instance.sign_url = sign_url
            #     #             data['sign_url'] = f'https://circle.sutpay.cn/{sign_url}'
            #     #         else:
            #     #             data['sign_url'] = instance.sign_url.url
            #     #         instance.applyment_state = 2
            #     #         instance.save()
            #     #         merchant.applyment_state = 2
            #     #         merchant.save()
            #     #     elif result['data']['open_status'] == 3:
            #     #         instance.applyment_state = 3
            #     #         instance.reject_reason = result['data']['open_result']
            #     #         instance.save()
            #     #         merchant.applyment_state = 3
            #     #         merchant.save()
            #     #         data['sign_url'] = ''
            #     #     else:
            #     #         data['sign_url'] = ''
            # elif instance.applyment_state == 4:
            #     data['sign_url'] = instance.sign_url.url
            #     result = check_sign_contract_result(merchant.ruiyinxinMerchantID)
            #     if result['data']['sign_status'] == 3:
            #         merchant.applyment_state = 1
            #         merchant.verify_state = 1
            #         merchant.save()
            #         instance.applyment_state = 1
            #         instance.audit_time = datetime.datetime.now()
            #         instance.save()
        return Response(data, status=status.HTTP_200_OK)

    def operation_mall(self, request):
        user = self.request.iser
        business_no = self.request.data.get('business_no', None)
        if not business_no:
            return Response({'error': '缺少商户号'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.is_mall not in [2, 3]:
            return Response({'error': '商户尚未通过入驻申请'}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.is_mall == 2:
            merchant.is_mall = 3
            merchant.save()
        else:
            merchant.is_mall = 2
            merchant.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def bank_qrcode(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '缺少商户号'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        bank_qrcode = MerchantBankQRCode.objects.filter(merchant_id=merchant.id).first()
        if bank_qrcode:
            bank_qrcode.visit += 1
            bank_qrcode.save()
            data = MerchantBankQRCodeRetrieveModelSerializer(bank_qrcode).data
        else:
            data = {}
        return Response(data, status=status.HTTP_200_OK)

    def download_bank_qrcode(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '缺少商户号'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        bank_qrcode = MerchantBankQRCode.objects.filter(merchant_id=merchant.id).first()
        if bank_qrcode:
            bank_qrcode.is_download = 1
            bank_qrcode.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def touch_big_turntable(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '请上传商户id'}, status=status.HTTP_400_BAD_REQUEST)
        # merchant = Merchant.objects.filter(merchantuser_id=user.id, wyfMerchantID=business_no).first()
        # if not merchant:
        #     return Response({'error': '无效商户id'}, status=status.HTTP_400_BAD_REQUEST)
        data_now = datetime.datetime.now()
        check_activity_id_list = MerchantEightEightActivity.objects.filter(activity_start_time__lte=data_now, activity_end_time__gte=data_now, activity_type=4).values_list('id', flat=True)
        if check_activity_id_list:
            # draw_end_time = check_activity.draw_end_time
            # available_end_time = check_activity.activity_end_time
            # activity_id = check_activity.activity_id
            activity_status = 3
            # c_time = available_end_time.strftime('%Y-%m-%d %H:%M:%S')
            white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id__in=check_activity_id_list).order_by('activity_id')
            if white_table:
                activity_id = white_table.first().activity_id
                check_activity = MerchantEightEightActivity.objects.get(id=activity_id)
                draw_end_time = check_activity.draw_end_time
                available_end_time = check_activity.activity_end_time
                c_time = available_end_time.strftime('%Y-%m-%d %H:%M:%S')
                check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id__in=check_activity_id_list).count()
                total_count = white_table.count() - check_draw
                account = f'{data_now.strftime("%Y%m%d")}{business_no}'
                if draw_end_time < data_now:
                    count = 0
                else:
                    if total_count <= 0:
                        count = 0
                    else:
                        count = total_count
                        check_draw_today = MerchantEightEightDraw.objects.filter(account=account)
                        # if check_draw_today:
                        #     count = 0
                        # else:
                        #     count = 1
            else:
                count = 0
                total_count = 0
                activity_id = 85
                check_activity = MerchantEightEightActivity.objects.get(id=85)
                c_time = '%Y-%m-%d %H:%M:%S'
            data = {}
            activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=activity_id)
            lists = []
            for activity_prize in activity_prize_set:
                lists.append({
                    'id': activity_prize.id,
                    'msg': activity_prize.prize_name,
                    'type': activity_prize.prize_type,
                    'amount': activity_prize.amount
                })
            data['lists'] = lists
            data['activity_description'] = check_activity.activity_description
            data['description'] = check_activity.activity_description
            data['count'] = count
            data['total_count'] = total_count
            data['activity_status'] = activity_status
            data['c_time'] = c_time
            data['activity_id'] = 5
            return Response(data, status=status.HTTP_200_OK)
        else:
            if data_now >= datetime.datetime.strptime("2024-12-29 23:59:59", "%Y-%m-%d %H:%M:%S"):
                return Response({'error': '活动已结束,感谢支持邮政活动'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({'error': '活动尚未开始,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)
            return Response({'error': '该活动仅限碰一下达标商户参加'}, status=status.HTTP_400_BAD_REQUEST)

    def touch_lucky_draw(self, request):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        merchant = Merchant.objects.filter(merchantuser_id=user.id, wyfMerchantID=business_no).first()
        if not merchant:
            return Response({'error': '无效商户id'}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_psbc_card == 0:
            return Response({'error': '请先完成验卡操作'}, status=status.HTTP_400_BAD_REQUEST)
        data_now = datetime.datetime.now()
        check_activity_id_list = MerchantEightEightActivity.objects.filter(activity_start_time__lte=data_now, activity_end_time__gte=data_now, activity_type=4).values_list('id', flat=True)
        if check_activity_id_list:
            white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id__in=check_activity_id_list)
            if not white_table:
                return Response({'error': '该活动仅限认证商户参加'}, status=status.HTTP_400_BAD_REQUEST)
            activity_id = white_table.first().activity_id
            check_activity = MerchantEightEightActivity.objects.get(id=activity_id)
            draw_end_time = check_activity.draw_end_time
            available_end_time = check_activity.activity_end_time
            available_begin_time = check_activity.activity_start_time
            if available_end_time < data_now:
                return Response({'error': '已过活动抽奖时间,请下期继续参与,多谢支持'}, status=status.HTTP_400_BAD_REQUEST)
            if available_begin_time > data_now:
                return Response({'error': '活动尚未开始领奖时间,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)
            check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=activity_id).count()
            # total_count = white_table.count() - check_draw
            account = f'{data_now.strftime("%Y%m%d")}{business_no}'
            if check_draw:
                return Response({'error': '抽奖次数已消耗完,感谢支持'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                check_draw_today = MerchantEightEightDraw.objects.filter(account=account)
                # if check_draw_today:
                #     return Response({'error': '今日抽奖次数已消耗完,明日再来'}, status=status.HTTP_400_BAD_REQUEST)
            draw_list = []
            draw_counts = MerchantEightEightDraw.objects.filter(activity_id=check_activity.id).values('win_type').annotate(Count('win_type'))
            draw_count_dict = {}
            for draw_count in draw_counts:
                draw_count_dict[draw_count['win_type']] = draw_count['win_type__count']
            activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id).exclude(prize_type=0)
            limit_count = {}
            for activity_prize in activity_prize_set:
                limit_count[activity_prize.id] = activity_prize.count
            for key, value in limit_count.items():
                if key in draw_count_dict:
                    if value > draw_count_dict[key]:
                        draw_list.append(key)
                else:
                    if value > 0:
                        draw_list.append(key)
            if draw_list:
                shuffle(draw_list)
                win_type = draw_list[0]
                activity_prize = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, id=win_type).first()
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                draw_data = {}
                draw_data['merchantuser_id'] = user.id
                draw_data['state'] = 1
                draw_data['desc'] = '微邮付商户碰一下达标回馈'
                draw_data['amount'] = activity_prize.amount
                draw_data['partner_trade_no'] = out_biz_no
                draw_data['win_type'] = win_type
                draw_data['business_no'] = business_no
                draw_data['account'] = account
                draw_data['level_id'] = merchant.level_id
                draw_data['activity_id'] = activity_id
                draw_data['expired_time'] = draw_end_time
                instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
                data = {}
                data["id"] = win_type
                data["take_id"] = instance.id
                data["amount"] = instance.amount
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["type"] = activity_prize.prize_type
                if activity_prize.prize_type == 2:
                    data["prize_count"] = activity_prize.prize_count
                else:
                    data["prize_count"] = 1

                if activity_prize.prize_type == 2:
                    alidiscountcoupon = activity_prize.alidiscountcoupon
                    alidiscountcoupon_id = alidiscountcoupon.id
                    prize_count = activity_prize.prize_count
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + prize_count
                        activity_new_remain_number = activity_origin_remain_number - prize_count
                        result = AliDiscountCoupon.objects.filter(id=alidiscountcoupon_id, send_count=activity_origin_send_count).update(
                            send_count=activity_new_send_count,
                            remain_number=activity_new_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    alidiscountcouponinfo_list = []
                    for i in range(prize_count):
                        alidiscountcouponinfo_data = {}
                        alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                        alidiscountcouponinfo_data['status'] = 0
                        alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                        if alidiscountcoupon.coupon_channel != 5:
                            out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                        else:
                            out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%04d" % randint(0, 9999)}'
                        alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                        alidiscountcouponinfo_data['mobile'] = user.mobile
                        alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                        alidiscountcouponinfo_data['coupon_channel'] = alidiscountcoupon.coupon_channel
                        alidiscountcouponinfo_data['merchantuser_id'] = user.id
                        alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                        alidiscountcouponinfo_list.append(alidiscountcouponinfo.id)
                    instance.alidiscountcouponinfo_list = json.dumps(alidiscountcouponinfo_list)
                    instance.save()
            else:
                activity_prize = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, prize_type=0).first()
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                draw_data = {}
                draw_data['merchantuser_id'] = user.id
                draw_data['state'] = 1
                draw_data['desc'] = '微邮付商户碰一下达标回馈'
                draw_data['amount'] = 0
                draw_data['partner_trade_no'] = out_biz_no
                draw_data['win_type'] = 6
                draw_data['business_no'] = business_no
                draw_data['account'] = account
                draw_data['level_id'] = merchant.level_id
                draw_data['activity_id'] = activity_id
                draw_data['expired_time'] = draw_end_time
                instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account)
                data = {}
                data["id"] = activity_prize.id
                data["take_id"] = instance.id
                data["amount"] = instance.amount
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["type"] = activity_prize.prize_type
                data["prize_count"] = 1
            try:
                check_activity.total_count += 1
                check_activity.save()
            except:
                pass
            return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
        else:
            if data_now >= datetime.datetime.strptime("2024-12-29 23:59:59", "%Y-%m-%d %H:%M:%S"):
                return Response({'error': '活动已结束,感谢支持邮政活动'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({'error': '活动尚未开始,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)
            return Response({'error': '该活动仅限碰一下达标商户参加'}, status=status.HTTP_400_BAD_REQUEST)

    def check_touch_merchant(self, request):
        '''校验中奖商户'''
        user = self.request.iser
        data_now = datetime.datetime.now()
        check_activity = MerchantEightEightActivity.objects.exclude(activity_id=3).filter(activity_start_time__lte=data_now, activity_end_time__gte=data_now, activity_type=2).first()
        if not check_activity:
            return Response({'business_no': '0000000000'}, status=status.HTTP_200_OK)
        merchant_set = Merchant.objects.filter(merchantuser_id=user.id)
        if not merchant_set:
            return Response({'business_no': '1000000000'}, status=status.HTTP_200_OK)
        draw_end_time = check_activity.draw_end_time
        available_end_time = check_activity.activity_end_time
        activity_id = check_activity.activity_id
        response_business_no = merchant_set.first().wyfMerchantID
        for merchant in merchant_set:
            business_no = merchant.wyfMerchantID
            white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id=activity_id)
            if not white_table:
                continue
            check_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=activity_id).count()
            total_count = white_table.count() - check_draw
            if total_count <= 0:
                continue
            response_business_no = business_no
        return Response({'business_no': response_business_no}, status=status.HTTP_200_OK)

    def trade_blessings_big_turntable(self, request):
        '''交易攒福礼大转盘'''
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '请上传商户id'}, status=status.HTTP_400_BAD_REQUEST)
        merchant = Merchant.objects.filter(merchantuser_id=user.id, wyfMerchantID=business_no).first()
        # if not merchant:
        #     return Response({'error': '无效商户id'}, status=status.HTTP_400_BAD_REQUEST)
        today = datetime.datetime.now()
        yesterday = today - datetime.timedelta(days=1)
        check_white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id=50)
        if check_white_table:
            check_white_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=50)
            if not check_white_draw:
                check_activity = MerchantEightEightActivity.objects.filter(id=50, activity_start_time__lte=today, activity_end_time__gte=today).first()
            else:
                # if user.id in [1, 2, 1412757, 3, 177, 903322, 1393826, 1635638]:
                if user.id in [2]:
                    check_activity = MerchantEightEightActivity.objects.get(id=49)
                else:
                    check_activity = MerchantEightEightActivity.objects.filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=3).exclude(activity_id__in=[3, 30, 47, 49, 50]).first()
        else:
            if user.id in [2]:
                check_activity = MerchantEightEightActivity.objects.get(id=49)
            else:
                check_activity = MerchantEightEightActivity.objects.filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=3).exclude(activity_id__in=[3, 30, 47, 49, 50]).first()
        if check_activity:
            draw_end_time = check_activity.draw_end_time
            available_end_time = check_activity.activity_end_time
            activity_id = check_activity.activity_id
            activity_status = 1
            remark = ''
            c_time = available_end_time.strftime('%Y-%m-%d %H:%M:%S')
            merchanteighteightorder = MerchantEightEightActivityOrder.objects.filter(trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), business_no=business_no, activity_id=activity_id).first()
            if not merchanteighteightorder:
                result = get_wyf_order_settle(business_no, yesterday.strftime("%Y-%m-%d 00:00:00"), yesterday.strftime("%Y-%m-%d 23:59:59"))
                merchanteighteightorder_data = {}
                merchanteighteightorder_data['trade_time'] = yesterday.strftime("%Y-%m-%d 00:00:00")
                merchanteighteightorder_data['business_no'] = business_no
                merchanteighteightorder_data['trade_amount'] = result
                merchanteighteightorder_data['activity_id'] = activity_id
                if merchant:
                    merchanteighteightorder_data['level_id'] = merchant.level_id
                if activity_id == 50:
                    if Decimal(result) >= Decimal('10'):
                        merchanteighteightorder_data['is_standard'] = 1
                    else:
                        merchanteighteightorder_data['is_standard'] = 0
                else:
                    if Decimal(result) >= Decimal('87'):
                        merchanteighteightorder_data['is_standard'] = 1
                    else:
                        merchanteighteightorder_data['is_standard'] = 0
                merchanteighteightorder, create = MerchantEightEightActivityOrder.objects.get_or_create(defaults=merchanteighteightorder_data, business_no=business_no, trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), activity_id=activity_id)
            if merchanteighteightorder.is_standard == 1:
                account = f'{today.strftime("%Y%m%d")}{business_no}'
                check_draw_today = MerchantEightEightDraw.objects.filter(account=account, activity_id=activity_id)
                if check_draw_today:
                    total_count = 0
                    activity_status = 2
                    remark = f'您已参与抽奖，请保持【微邮付】码牌收款当日达88元，次日即可参与抽奖'
                else:
                    if activity_id == 50:
                        total_count = 1
                    else:
                        check_draw_today = MerchantEightEightDraw.objects.exclude(win_type=6).filter(business_no=business_no, activity_id__in=[51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,49,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84]).count()
                        if check_draw_today >= 3:
                            total_count = 0
                            activity_status = 2
                            remark = f'周期内活动参与3次,已达上限,感谢支持邮政活动'
                        else:
                            total_count = 1
            else:
                activity_status = 2
                remark = f'您昨日交易为{merchanteighteightorder.trade_amount}元，未满足抽奖标准，请使用【微邮付】码牌收款达88元，次日即可参与抽奖'
                total_count = 0
            data = {}
            activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id)
            lists = []
            for activity_prize in activity_prize_set:
                lists.append({
                    'id': activity_prize.id,
                    'msg': activity_prize.prize_name,
                    'type': activity_prize.prize_type,
                    'amount': activity_prize.amount
                })
            data['lists'] = lists
            data['activity_description'] = check_activity.activity_description
            data['description'] = check_activity.activity_description
            data['total_count'] = total_count
            data['activity_status'] = activity_status
            data['c_time'] = c_time
            data['activity_id'] = 5
            data['remark'] = remark
            return Response(data, status=status.HTTP_200_OK)
        else:
            data = {}
            activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=51)
            lists = []
            for activity_prize in activity_prize_set:
                lists.append({
                    'id': activity_prize.id,
                    'msg': activity_prize.prize_name,
                    'type': activity_prize.prize_type,
                    'amount': activity_prize.amount
                })
            data['lists'] = lists
            data['activity_description'] = '''①活动对象：广东省达标微邮付商户； 
②活动时间：2025年2月26日9:00:00至3月31日23:59:59； 
③活动规则： 
1）鸿运盈财礼：活动期间，广东省微邮付潜力商户单日交易金额满10元，次日登录活动页面即可获得一次“鸿运盈财礼”抽奖机会，每个潜力商户最多可获得1次“鸿运盈财礼”抽奖机会； 
2）日进斗金礼：广东微邮付商户单日交易金额满88元，次日登录活动页面即可获得一次“日进斗金礼”抽奖机会，每个商户最多可获得3次“日进斗金礼”抽奖机会； ④抽奖机会说明：商户当日交易达标后，须次日登录活动页面才可获得抽奖机会。若次日未登录活动页面，则视为放弃抽奖机会。抽奖机会有效期为获取日起至2025年3月31日23:59:59，逾期未使用则自动失效，抽奖机会次数可叠加。 
④活动奖品：价值3.88元、8.88元、12.88元、18元、38元、88元、388元支付宝权益，每日限量投放，先到先得。中奖后通过填写支付宝账户信息领取。领取后可在支付宝APP-我的-账单中查看到账情况。中奖后需在3月31日23:59:59前领取，逾期未领取视为放弃奖品。'''
            data['description'] = '''①活动对象：广东省达标微邮付商户； 
②活动时间：2025年2月26日9:00:00至3月31日23:59:59； 
③活动规则： 
1）鸿运盈财礼：活动期间，广东省微邮付潜力商户单日交易金额满10元，次日登录活动页面即可获得一次“鸿运盈财礼”抽奖机会，每个潜力商户最多可获得1次“鸿运盈财礼”抽奖机会； 
2）日进斗金礼：广东微邮付商户单日交易金额满88元，次日登录活动页面即可获得一次“日进斗金礼”抽奖机会，每个商户最多可获得3次“日进斗金礼”抽奖机会； ④抽奖机会说明：商户当日交易达标后，须次日登录活动页面才可获得抽奖机会。若次日未登录活动页面，则视为放弃抽奖机会。抽奖机会有效期为获取日起至2025年3月31日23:59:59，逾期未使用则自动失效，抽奖机会次数可叠加。 
④活动奖品：价值3.88元、8.88元、12.88元、18元、38元、88元、388元支付宝权益，每日限量投放，先到先得。中奖后通过填写支付宝账户信息领取。领取后可在支付宝APP-我的-账单中查看到账情况。中奖后需在3月31日23:59:59前领取，逾期未领取视为放弃奖品。'''
            data['total_count'] = 0
            data['activity_status'] = 2
            data['activity_id'] = 5
            if today >= datetime.datetime.strptime("2025-03-31 23:59:59", "%Y-%m-%d %H:%M:%S"):
                data['remark'] = '活动已结束，感谢支持邮政活动'
            else:
                data['remark'] = '活动尚未开始，敬请期待'
            return Response(data, status=status.HTTP_200_OK)

    def trade_blessings_lucky_draw(self, request):
        '''交易攒福礼抽奖'''
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        if not business_no:
            return Response({'error': '请上传商户号'}, status=status.HTTP_400_BAD_REQUEST)
        merchant = Merchant.objects.filter(merchantuser_id=user.id, wyfMerchantID=business_no).first()
        if not merchant:
            return Response({'error': '无效商户id'}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_psbc_card == 0:
            return Response({'error': '请先完成验卡操作'}, status=status.HTTP_400_BAD_REQUEST)
        today = datetime.datetime.now()
        yesterday = today - datetime.timedelta(days=1)
        check_white_table = MerchantEightEightWhiteTable.objects.filter(business_no=business_no, activity_id=50)
        if check_white_table:
            check_white_draw = MerchantEightEightDraw.objects.filter(business_no=business_no, activity_id=50)
            if not check_white_draw:
                check_activity = MerchantEightEightActivity.objects.filter(id=50, activity_start_time__lte=today, activity_end_time__gte=today).first()
            else:
                if user.id in [2]:
                    check_activity = MerchantEightEightActivity.objects.get(id=49)
                else:
                    check_activity = MerchantEightEightActivity.objects.filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=3).exclude(activity_id__in=[3, 30, 47, 49, 50]).first()
        else:
            if user.id in [2]:
                check_activity = MerchantEightEightActivity.objects.get(id=49)
            else:
                check_activity = MerchantEightEightActivity.objects.filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=3).exclude(activity_id__in=[3, 30, 47, 49, 50]).first()
        # if user.id in [2, 1412757, 3]:
        #     check_activity = MerchantEightEightActivity.objects.get(id=30)
        # else:
        #     check_activity = MerchantEightEightActivity.objects.exclude(activity_id__in=[30, 47]).filter(activity_start_time__lte=today, activity_end_time__gte=today, activity_type=3).first()
        if check_activity:
            draw_end_time = check_activity.draw_end_time
            available_end_time = check_activity.activity_end_time
            available_begin_time = check_activity.activity_start_time
            activity_id = check_activity.activity_id
            if available_end_time < today:
                return Response({'error': '已过活动抽奖时间,请下期继续参与,多谢支持'}, status=status.HTTP_400_BAD_REQUEST)
            if available_begin_time > today:
                return Response({'error': '活动尚未开始领奖时间,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)
            merchanteighteightorder = MerchantEightEightActivityOrder.objects.filter(trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"), business_no=business_no).first()
            if not merchanteighteightorder:
                result = get_wyf_order_settle(business_no, yesterday.strftime("%Y-%m-%d 00:00:00"), yesterday.strftime("%Y-%m-%d 23:59:59"))
                merchanteighteightorder_data = {}
                merchanteighteightorder_data['trade_time'] = yesterday.strftime("%Y-%m-%d 00:00:00")
                merchanteighteightorder_data['business_no'] = business_no
                merchanteighteightorder_data['trade_amount'] = result
                merchanteighteightorder_data['activity_id'] = activity_id
                merchanteighteightorder_data['level_id'] = merchant.level_id
                if activity_id == 50:
                    if Decimal(result) >= Decimal('10'):
                        merchanteighteightorder_data['is_standard'] = 1
                    else:
                        merchanteighteightorder_data['is_standard'] = 0
                else:
                    if Decimal(result) >= Decimal('87'):
                        merchanteighteightorder_data['is_standard'] = 1
                    else:
                        merchanteighteightorder_data['is_standard'] = 0
                merchanteighteightorder, create = MerchantEightEightActivityOrder.objects.get_or_create(defaults=merchanteighteightorder_data, business_no=business_no, trade_time=yesterday.strftime("%Y-%m-%d 00:00:00"))
            if merchanteighteightorder.is_standard == 0:
                return Response({'error': f'该活动仅限交易达标商户参加,商户昨日交易金额{merchanteighteightorder.trade_amount}元'}, status=status.HTTP_400_BAD_REQUEST)

            account = f'{today.strftime("%Y%m%d")}{business_no}'
            check_draw_today = MerchantEightEightDraw.objects.filter(account=account, activity_id=activity_id)
            if check_draw_today:
                return Response({'error': '今日抽奖次数已消耗完,明日再来'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if activity_id != 50:
                    check_draw_today = MerchantEightEightDraw.objects.exclude(win_type=6).filter(business_no=business_no, activity_id__in=[51, 52, 53, 54, 55, 56,57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 49, 66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84]).count()
                    if check_draw_today >= 3:
                        return Response({'error': '周期内活动参与3次,已达上限,感谢支持邮政活动'}, status=status.HTTP_400_BAD_REQUEST)
            index = 1
            draw_list = []
            draw_counts = MerchantEightEightDraw.objects.filter(activity_id=check_activity.id, index=index).values('win_type').annotate(Count('win_type'))
            draw_count_dict = {}
            for draw_count in draw_counts:
                draw_count_dict[draw_count['win_type']] = draw_count['win_type__count']
            activity_prize_set = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id).exclude(prize_type=0)
            limit_count = {}
            if index == 1:
                for activity_prize in activity_prize_set:
                    limit_count[activity_prize.id] = activity_prize.count
            else:
                for activity_prize in activity_prize_set:
                    limit_count[activity_prize.id] = activity_prize.second_count
            for key, value in limit_count.items():
                if key in draw_count_dict:
                    if value > draw_count_dict[key]:
                        draw_list.append(key)
                else:
                    if value > 0:
                        draw_list.append(key)
            if activity_id == 50:
                is_refresh = 1
            else:
                is_refresh = 0
            if draw_list:
                shuffle(draw_list)
                win_type = draw_list[0]
                activity_prize = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, id=win_type).first()
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                draw_data = {}
                draw_data['merchantuser_id'] = user.id
                draw_data['state'] = 1
                draw_data['desc'] = '微邮付商户交易攒福礼达标回馈'
                draw_data['amount'] = activity_prize.amount
                draw_data['partner_trade_no'] = out_biz_no
                draw_data['win_type'] = win_type
                draw_data['business_no'] = business_no
                draw_data['account'] = account
                draw_data['level_id'] = merchant.level_id
                draw_data['activity_id'] = activity_id
                draw_data['expired_time'] = draw_end_time
                draw_data['index'] = index
                instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account, activity_id=activity_id)
                data = {}
                data["id"] = win_type
                data["take_id"] = instance.id
                data["amount"] = instance.amount
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["type"] = activity_prize.prize_type
                if activity_prize.prize_type == 2:
                    data["prize_count"] = activity_prize.prize_count
                else:
                    data["prize_count"] = 1
                data["is_refresh"] = is_refresh
                if activity_prize.prize_type == 2:
                    alidiscountcoupon = activity_prize.alidiscountcoupon
                    alidiscountcoupon_id = alidiscountcoupon.id
                    prize_count = activity_prize.prize_count
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + prize_count
                        activity_new_remain_number = activity_origin_remain_number - prize_count
                        result = AliDiscountCoupon.objects.filter(id=alidiscountcoupon_id, send_count=activity_origin_send_count).update(
                            send_count=activity_new_send_count,
                            remain_number=activity_new_remain_number
                        )
                        if result == 0:
                            continue
                        break
                    alidiscountcouponinfo_list = []
                    for i in range(prize_count):
                        alidiscountcouponinfo_data = {}
                        alidiscountcouponinfo_data['alidiscountcoupon_id'] = alidiscountcoupon.id
                        alidiscountcouponinfo_data['status'] = 0
                        alidiscountcouponinfo_data['template_id'] = alidiscountcoupon.template_id
                        if alidiscountcoupon.coupon_channel != 5:
                            out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                        else:
                            out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%04d" % randint(0, 9999)}'
                        alidiscountcouponinfo_data['out_biz_no'] = out_biz_no
                        alidiscountcouponinfo_data['mobile'] = user.mobile
                        alidiscountcouponinfo_data['gmt_distributed'] = datetime.datetime.now()
                        alidiscountcouponinfo_data['coupon_channel'] = alidiscountcoupon.coupon_channel
                        alidiscountcouponinfo_data['merchantuser_id'] = user.id
                        alidiscountcouponinfo, crete = AliDiscountCouponInfo.objects.get_or_create(defaults=alidiscountcouponinfo_data, out_biz_no=out_biz_no)
                        alidiscountcouponinfo_list.append(alidiscountcouponinfo.id)
                    instance.alidiscountcouponinfo_list = json.dumps(alidiscountcouponinfo_list)
                    instance.save()
            else:
                activity_prize = MerchantEightEightActivityPrize.objects.filter(activity_id=check_activity.id, prize_type=0).first()
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                draw_data = {}
                draw_data['merchantuser_id'] = user.id
                draw_data['state'] = 1
                draw_data['desc'] = '微邮付商户交易攒福礼达标回馈'
                draw_data['amount'] = 0
                draw_data['partner_trade_no'] = out_biz_no
                draw_data['win_type'] = 6
                draw_data['business_no'] = business_no
                draw_data['account'] = account
                draw_data['level_id'] = merchant.level_id
                draw_data['activity_id'] = activity_id
                draw_data['expired_time'] = draw_end_time
                draw_data['index'] = index
                instance, create = MerchantEightEightDraw.objects.get_or_create(defaults=draw_data, account=account, activity_id=activity_id)
                data = {}
                data["id"] = activity_prize.id
                data["take_id"] = instance.id
                data["amount"] = instance.amount
                data["activity_name"] = ''
                data["msg"] = ''
                data["available_time"] = ''
                data["win_type_str"] = instance.get_win_type_display()
                data["win_type"] = instance.win_type
                data["type"] = activity_prize.prize_type
                data["prize_count"] = 1
                data["is_refresh"] = is_refresh
            try:
                check_activity.total_count += 1
                check_activity.save()
            except:
                pass
            return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
        else:
            if today >= datetime.datetime.strptime("2025-03-31 23:59:59", "%Y-%m-%d %H:%M:%S"):
                return Response({'error': '活动已结束,感谢支持邮政活动'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({'error': '活动尚未开始,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)


class GoodsModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', )
    filter_class = GoodsFilter

    def get_serializer_class(self):
        if self.action == 'list':
            return GoodsListModelSerializer
        else:
            return GoodsRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        sale_sort = self.request.query_params.get('sale_sort', None)
        price_sort = self.request.query_params.get('price_sort', None)
        soldout = self.request.query_params.get('soldout', '')
        if soldout == '1':
            queryset = Goods.objects.filter(stock__gt=0, merchant__merchantuser_id=user.id).distinct().order_by('-stock')
        elif soldout == '2':
            queryset = Goods.objects.filter(stock=0, merchant__merchantuser_id=user.id).distinct().order_by('-stock')
        else:
            queryset = Goods.objects.filter(merchant__merchantuser_id=user.id).distinct().order_by('-stock')
        if sale_sort == '1':
            queryset = queryset.order_by('sales', 'id')
        elif sale_sort == '2':
            queryset = queryset.order_by('-sales', 'id')
        if price_sort == '1':
            queryset = queryset.order_by('price', 'id')
        elif price_sort == '2':
            queryset = queryset.order_by('-price', 'id')
        return queryset.filter(equityID__isnull=True)

    def get_serializer_context(self):
        user = self.request.iser
        return {'user': user}

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        user = self.request.iser
        on__count = queryset.filter(is_launched=1, merchant__merchantuser_id=user.id).count()
        down__count = queryset.count() - on__count
        business_no = self.request.query_params.get('business_no', None)
        if business_no:
            merchant = Merchant.objects.filter(wyfMerchantID=business_no).first()
            if merchant:
                store_address = merchant.store_address
            else:
                store_address = ''
        else:
            store_address = ''
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        self.request.data['on__count'] = str(on__count)
        self.request.data['down__count'] = str(down__count)
        self.request.data['store_address'] = str(store_address)
        is_launched = self.request.query_params.get('is_launched', None)
        if is_launched in ['0', '1']:
            if is_launched == '0':
                queryset = queryset.exclude(is_launched=1, merchant__merchantuser_id=user.id)
            else:
                queryset = queryset.filter(is_launched=1, merchant__merchantuser_id=user.id)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def upload_image(self, request):
        user = self.request.iser
        img = self.request.FILES.get('img', None)
        business_no = self.request.data.get('business_no', None)
        if not all([img, business_no]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if img.size > 2097152:
            return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = img.read()
        img.seek(0)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no)
        except:
            return Response({'error': '无效商户号'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            img_id = f'youhuiquanyi/{business_no}/goods_image{"%06d" % randint(0, 999999)}.png'
            mid_img = pic_upload(img_str, key=img_id)
        except Exception as e:
            logger.error(e)
            return Response({'error': '图片上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'success': '操作成功', 'img_id': f'https://circle.sutpay.cn/{img_id}'}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        if instance.is_launched == 2:
            return Response({'error': '已存在待审核修改单,请耐心等待客服审核'}, status=status.HTTP_400_BAD_REQUEST)
        applyment = GoodsModifyApplyment.objects.filter(goods_id=instance.id, applyment_status=1)
        if applyment:
            return Response({'error': '已存在待审核修改单,请耐心等待客服审核'}, status=status.HTTP_400_BAD_REQUEST)
        name = self.request.data.get('name', None)
        caption = self.request.data.get('caption', None)
        desc_detail = self.request.data.get('desc_detail', None)
        desc_pack = self.request.data.get('desc_pack', '')
        price = self.request.data.get('price', None)
        market_price = self.request.data.get('market_price', None)
        default_image = self.request.data.get('default_image', None)
        image_array = self.request.data.get('image_array', None)
        stock = self.request.data.get('stock', None)
        manufacturer = self.request.data.get('manufacturer', None)
        specifications = self.request.data.get('specifications', None)
        is_launched = self.request.data.get('is_launched', None)
        if not name:
            return Response({'error': '请输入商品名称。'}, status=status.HTTP_400_BAD_REQUEST)
        if len(name) > 128:
            return Response({'error': '您输入的商品名称有误，请重新输入。'}, status=status.HTTP_400_BAD_REQUEST)
        if not caption:
            return Response({'error': '请输入商品品牌。'}, status=status.HTTP_400_BAD_REQUEST)
        if len(caption) > 50:
            return Response({'error': '您输入的品牌有误，请重新输入。'}, status=status.HTTP_400_BAD_REQUEST)
        if not desc_detail:
            return Response({'error': '请输入商品介绍。'}, status=status.HTTP_400_BAD_REQUEST)
        if not default_image:
            return Response({'error': '请输入商品封面图。'}, status=status.HTTP_400_BAD_REQUEST)
        if not manufacturer:
            return Response({'error': '请输入商品厂商。'}, status=status.HTTP_400_BAD_REQUEST)
        if len(manufacturer) > 32:
            return Response({'error': '您输入的厂商有误，请重新输入。'}, status=status.HTTP_400_BAD_REQUEST)
        if not specifications:
            return Response({'error': '请输入商品规格。'}, status=status.HTTP_400_BAD_REQUEST)
        if len(specifications) > 8:
            return Response({'error': '您输入的商品规格有误，请重新输入。'}, status=status.HTTP_400_BAD_REQUEST)
        if not image_array:
            return Response({'error': '请输入商品轮播图。'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            desc_detail = json.dumps(desc_detail)
            # image_array = json.dumps(image_array)
        except:
            return Response({'error': '商品详情数据格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        applyment_status = 0
        old_goods = GoodsRetrieveModelSerializer(instance).data
        check_word = ['name', 'desc_detail', 'price', 'default_image', 'manufacturer', 'specifications', 'market_price', 'caption', 'desc_pack']
        update_word = []
        try:
            if old_goods['goodsimage_set'] != self.request.data.get('image_array', None):
                applyment_status = 1
                update_word.append('goodsimage_set')
        except:
            pass
        for word in check_word:
            try:
                if word in ['price', 'market_price']:
                    if Decimal(old_goods[word]) != Decimal(self.request.data.get(word, None)):
                        applyment_status = 1
                        update_word.append(word)
                else:
                    if old_goods[word] != self.request.data.get(word, None):
                        applyment_status = 1
                        update_word.append(word)
            except:
                pass
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                if applyment_status:
                    instance.name = name
                    instance.caption = caption
                    instance.desc_detail = desc_detail
                    instance.desc_pack = desc_pack
                    instance.price = price
                    instance.market_price = market_price
                    instance.default_image = default_image.replace('https://circle.sutpay.cn/', '')
                    instance.manufacturer = manufacturer
                    instance.specifications = specifications
                    instance.is_launched = is_launched
                    instance.remain_stock = instance.remain_stock + Decimal(stock) - instance.stock
                    instance.stock = Decimal(stock)
                    instance.save()
                    applyment_data = {}
                    for word in update_word:
                        if word != 'goodsimage_set':
                            applyment_data[word] = old_goods[word]
                    if old_goods['goodsimage_set'] != self.request.data.get('image_array', None):
                        goodsimage_set = instance.goodsimage_set.all().delete()
                        applyment_data['image_array'] = json.dumps(old_goods['goodsimage_set'])
                        for image in image_array:
                            GoodsImage.objects.create(
                                goods_id=instance.id,
                                image=image.replace('https://circle.sutpay.cn/', '')
                            )
                    applyment_data['create_time'] = datetime.datetime.now()
                    applyment_data['is_launched'] = old_goods['is_launched']
                    applyment_data['stock'] = old_goods['stock']
                    applyment_data['goods_id'] = instance.id
                    applyment_data['applyment_status'] = 2
                    # applyment_data['companyuser_id'] = user.id
                    # applyment_data['level_id'] = user.level_id
                    applyment_data['update_word'] = json.dumps(update_word)
                    # applyment, create = GoodsModifyApplyment.objects.get_or_create(goods_id=instance.id, applyment_status=2, defaults=applyment_data)
                    applyment = GoodsModifyApplyment.objects.create(**applyment_data)
                    # eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=3)
                    # task_id = automatic_audit_applyment.apply_async(({"applyment_id": applyment.id},), eta=eta)
                    transaction.savepoint_commit(save_id)
                    return Response({'success': '提交修改成功,请耐心等待客服审核生效'}, status=status.HTTP_200_OK)
                else:
                    instance.remain_stock = instance.remain_stock + Decimal(stock) - instance.stock
                    instance.stock = Decimal(stock)
                    instance.is_launched = is_launched
                    instance.save()
                    check_query = LaunchedGoods.objects.filter(goods_id=instance.id, is_self=1).first()
                    if not check_query:
                        launched_goods_data = {}
                        launched_goods_data['name'] = instance.name
                        launched_goods_data['caption'] = instance.caption
                        launched_goods_data['goods_id'] = instance.id
                        launched_goods_data['category_id'] = instance.category_id
                        launched_goods_data['price'] = instance.price
                        launched_goods_data['point'] = instance.point
                        launched_goods_data['stock'] = instance.stock
                        launched_goods_data['is_launched'] = 0
                        launched_goods_data['create_time'] = datetime.datetime.now()
                        launched_goods_data['is_self'] = 1
                        LaunchedGoods.objects.get_or_create(defaults=launched_goods_data, goods_id=instance.id, is_self=1)
                    else:
                        check_query.stock = Decimal(stock)
                        check_query.is_launched = is_launched
                        check_query.save()
                    applyment_data = {}
                    applyment_data['stock'] = old_goods['stock']
                    applyment_data['is_launched'] = old_goods['is_launched']
                    applyment_data['applyment_status'] = 2
                    applyment_data['create_time'] = datetime.datetime.now()
                    applyment = GoodsModifyApplyment.objects.create(**applyment_data)
                    transaction.savepoint_commit(save_id)
                    return Response({'success': '提交修改成功'}, status=status.HTTP_200_OK)
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '提交失败,请联系管理员处理。'}, status=status.HTTP_400_BAD_REQUEST)

    def create(self, request, *args, **kwargs):
        user = self.request.iser
        name = self.request.data.get('name', None)
        caption = self.request.data.get('caption', None)
        desc_detail = self.request.data.get('desc_detail', None)
        desc_pack = self.request.data.get('desc_pack', '')
        price = self.request.data.get('price', None)
        market_price = self.request.data.get('market_price', None)
        default_image = self.request.data.get('default_image', None)
        image_array = self.request.data.get('image_array', None)
        stock = self.request.data.get('stock', None)
        business_no = self.request.data.get('business_no', None)
        manufacturer = self.request.data.get('manufacturer', None)
        specifications = self.request.data.get('specifications', None)
        is_launched = self.request.data.get('is_launched', None)
        barcode = self.request.data.get('barcode', None)
        if not all([name, caption, desc_detail, price, market_price, default_image, image_array, stock, business_no, manufacturer, specifications]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            desc_detail = json.dumps(desc_detail)
            # image_array = json.dumps(image_array)
        except:
            return Response({'error': '商品详情数据格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            merchant = Merchant.objects.get(wyfMerchantID=business_no, merchantuser_id=user.id)
        except:
            return Response({"error": "无效商户号"}, status=status.HTTP_400_BAD_REQUEST)
        if merchant.is_mall not in [2, 3]:
            return Response({"error": "商户未入驻微邮惠商城"}, status=status.HTTP_400_BAD_REQUEST)
        instance = Goods.objects.filter(merchant_id=merchant.id, name=name)
        if instance:
            return Response({"error": "商品名称重复"}, status=status.HTTP_400_BAD_REQUEST)
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                goods_data = {}
                goods_data['name'] = name
                goods_data['caption'] = caption
                goods_data['category_id'] = 1
                goods_data['desc_detail'] = desc_detail
                goods_data['desc_pack'] = desc_pack
                goods_data['price'] = price
                goods_data['market_price'] = market_price
                goods_data['default_image'] = default_image.replace('https://circle.sutpay.cn/', '')
                goods_data['stock'] = stock
                goods_data['merchant_id'] = merchant.id
                goods_data['manufacturer'] = manufacturer
                goods_data['specifications'] = specifications
                goods_data['is_launched'] = 2
                goods_data['remain_stock'] = stock
                goods_data['is_settlement'] = 1
                goods_data['longitude'] = merchant.longitude
                goods_data['latitude'] = merchant.latitude
                goods_data['order_species'] = 2
                area = GoodsAreaCode.objects.filter(district_name=merchant.district_name, prov_name=merchant.prov_name, city_name=merchant.city_name).first()
                if area:
                    goods_data['area_id'] = area.id
                instance, create = Goods.objects.get_or_create(defaults=goods_data, name=name, merchant_id=merchant.id)
                for image in image_array:
                    GoodsImage.objects.create(
                        goods_id=instance.id,
                        image=image.replace('https://circle.sutpay.cn/', '')
                    )
                applyment_data = {}
                applyment_data['goods_id'] = instance.id
                applyment_data['merchant_id'] = merchant.id
                applyment_data['applyment_type'] = 2
                applyment_data['barcode'] = barcode
                applyment_data['create_time'] = datetime.datetime.now()
                applyment = GoodsModifyApplyment.objects.create(**applyment_data)
                transaction.savepoint_commit(save_id)
                eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=3)
                task_id = automatic_audit_applyment.apply_async(({"applyment_id": applyment.id},), eta=eta)
                return Response({'success': '提交成功,请耐心等待客服审核生效', 'goods_id': instance.id}, status=status.HTTP_200_OK)
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                error_enum = {
                    "name": '商品名称',
                    "caption": '品牌',
                    "desc_detail": '商品介绍',
                    "market_price": '市场价',
                    "default_image": '商品封面图',
                    "manufacturer": '厂商',
                    "specifications": '规格',
                    "remain_stock": '库存',
                    "image": '商品轮播图'
                }
                for key, value in error_enum.items():
                    if key in e:
                        result = f'您输入的{value}有误，请重新输入。'
                        break
                    else:
                        result = f'提交失败,请联系管理员处理。'
                return Response({'error': result}, status=status.HTTP_400_BAD_REQUEST)

    def sweep_code_identification(self, request):
        barcode = self.request.query_params.get('barcode', None)
        business_no = self.request.query_params.get('business_no', None)
        if not all([barcode, business_no]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if not barcode:
            return Response({'error': 'barcode是空格'}, status=status.HTTP_400_BAD_REQUEST)
        if barcode == ' ':
            return Response({'error': 'barcode是空格'}, status=status.HTTP_400_BAD_REQUEST)
        url = f'https://api.jisuapi.com/barcode2/query?appkey=332d5b0000350eb8&barcode={barcode}'
        response = requests.get(url=url)
        result = response.json()
        data = {}
        data['name'] = ''
        data['default_image'] = ''
        data['price'] = ''
        data['sales'] = ''
        data['goodsimage_set'] = []
        data['desc_detail'] = [{
                    "b_title": "商品说明",
                    "arr2": []
                }]
        data['market_price'] = '0.00'
        data['manufacturer'] = ''
        data['specifications'] = ''
        data['stock'] = 0
        data['caption'] = ''
        try:
            if result['status'] != 0:
                return Response(data, status=status.HTTP_200_OK)
            result = result['result']
            pic_url = result['pic']
            if 'http' in pic_url:
                try:
                    img_id = f'youhuiquanyi/{business_no}/goods_image{"%06d" % randint(0, 999999)}.png'
                    mid_img = pic_upload(requests.get(url=pic_url).content, key=img_id)
                    data['default_image'] = f'https://circle.sutpay.cn/{img_id}'
                    data['goodsimage_set'] = [f'https://circle.sutpay.cn/{img_id}']
                    data['desc_detail'] = [{
                        "b_title": "商品说明",
                        "arr2":[{
                            "title": "",
                            "text": "",
                            "img": f'https://circle.sutpay.cn/{img_id}'
                        }]
                    }]
                except Exception as e:
                    pass
            data['name'] = result['name']
            if result['price']:
                data['price'] = result['price']
            else:
                data['price'] = '0.00'
            data['manufacturer'] = result['company']
            data['caption'] = result['brand']
            data['specifications'] = result['type']
        except:
            pass
        return Response(data, status=status.HTTP_200_OK)


class MerchantBusinessCategoryModelViewSet(ModelViewSet):

    queryset = MerchantBusinessCategory.objects.all()
    serializer_class = MerchantBusinessCategoryModelSerializer


class WaivePaymentActivityModelViewSet(ModelViewSet):

    serializer_class = WaivePaymentActivityModelSerializer
    filter_class = WaivePaymentMerchantFilter
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)

    def get_queryset(self):
        user = self.request.iser
        queryset = WaivePaymentMerchant.objects.filter(payment_state=5, waivepaymentactivity__activity_state=2, merchant_user_id=user.id, waivepaymentactivity__available_end_time__gte=datetime.datetime.now())
        return queryset

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        order_set = instance.waivepaymentorder_set.all()
        is_hit_order = order_set.filter(is_hit=1).first()
        order_set = order_set[:20]
        data = {}
        scrollText1 = [{}]
        scrollText2 = ['']
        scrollText3 = ['']
        while True:
            if len(scrollText1) >= 20:
                break
            for order in order_set:
                scrollText1.append({
                    "date": order.trade_time_end.strftime('%m-%d'),
                    "time": order.trade_time_end.strftime('%H:%M:%S'),
                })
                scrollText2.append(order.trade_type)
                scrollText3.append(f'¥{order.trade_money}')
        if instance.payment_type == 1:
            scrollText1.append({
                "date": is_hit_order.trade_time_end.strftime('%m-%d'),
                "time": is_hit_order.trade_time_end.strftime('%H:%M:%S')
            })
            scrollText2.append(is_hit_order.trade_type)
            scrollText3.append(f'¥{is_hit_order.trade_money}')
        else:
            scrollText1.append({
                "date": '',
                "time": ''
            })
            scrollText2.append('')
            scrollText3.append('')
        data['scrollText1'] = scrollText1
        data['scrollText2'] = scrollText2
        data['scrollText3'] = scrollText3
        return Response(data, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.payment_type == 1:
            instance.payment_state = 1
        else:
            instance.payment_state = 7
        instance.received_time = datetime.datetime.now()
        instance.save()
        return Response({'success': '抽奖完成', 'id': instance.id, 'amount': f'¥{instance.amount}', 'payment_type': instance.payment_type}, status=status.HTTP_200_OK)


class WaivePaymentMerchantModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_class = WaivePaymentMerchantFilter
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)

    def get_queryset(self):
        user = self.request.iser
        queryset = WaivePaymentMerchant.objects.filter(payment_state__in=[1, 2, 3, 7], merchant_user_id=user.id)
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return WaivePaymentMerchantListModelSerializer
        else:
            return WaivePaymentMerchantRetrieveModelSerializer

    def check_company_mobile(self, request):
        company_mobile = self.request.data.get('company_mobile', None)
        if not company_mobile:
            return Response({'error': '请上传客户经理手机号'}, status=status.HTTP_400_BAD_REQUEST)
        user = User.objects.filter(mobile=company_mobile, role_id__in=[2, 3], level__prov_id=7330, is_active=1)
        if not user:
            return Response({'error': '校验不通过'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'success': '校验通过'}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.payment_state == 2:
            return Response({'error': '不可重复领奖'}, status=status.HTTP_400_BAD_REQUEST)
        # company_mobile = self.request.data.get('company_mobile', None)
        # if instance.payment_state == 1:
        #     if not company_mobile:
        #         return Response({'error': '请上传客户经理手机号'}, status=status.HTTP_400_BAD_REQUEST)
        #     user = User.objects.filter(mobile=company_mobile, role_id__in=[2, 3], level__prov_id=7330, is_active=1)
        #     if not user:
        #         return Response({'error': '校验不通过'}, status=status.HTTP_400_BAD_REQUEST)
        account = self.request.data.get('account', None)
        name = self.request.data.get('name', None)
        waivepaymentactivity = instance.waivepaymentactivity
        alipay_obj = C_AlipayOpen()
        trans_amount = str(instance.amount)
        order_title = waivepaymentactivity.desc
        out_biz_no = instance.partner_trade_no
        identity = account
        name = name
        instance.payment_state = 2
        instance.save()
        result = json.loads(alipay_obj.transunitransfer_login_id(identity, name, out_biz_no, trans_amount, order_title))
        if result['code'] != '10000':
            instance.return_msg = result['sub_msg']
            instance.payment_state = 3
            instance.account = account
            instance.name = name
            # if company_mobile:
            #     instance.company_mobile = company_mobile
            instance.save()
            return Response({'error': '领取失败', 'return_msg': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
        else:
            instance.payment_no = result['pay_fund_order_id']
            instance.payment_time = result['trans_date']
            instance.payment_state = 2
            instance.account = account
            instance.name = name
            instance.return_msg = ''
            # if company_mobile:
            #     instance.company_mobile = company_mobile
            instance.save()
            waivepaymentactivity.receive_amount += instance.amount
            waivepaymentactivity.save()
            return Response({'success': '领取成功'}, status=status.HTTP_200_OK)


class MerchantEightEightDrawModelViewSet(ModelViewSet):

    def get_queryset(self):
        user = self.request.iser
        business_no = self.request.query_params.get('business_no', None)
        activity_type = self.request.query_params.get('activity_type', None)
        today = datetime.datetime.now()
        if business_no:
            queryset = MerchantEightEightDraw.objects.filter(merchantuser_id=user.id, business_no=business_no, expired_time__gte=today)
        else:
            queryset = MerchantEightEightDraw.objects.filter(merchantuser_id=user.id, expired_time__gte=today)
        if activity_type:
            activity_id_lsit = MerchantEightEightActivity.objects.filter(activity_type=activity_type).values_list('id', flat=True)
            queryset = queryset.filter(activity_id__in=activity_id_lsit)
        return queryset.exclude(win_type=6)

    def get_serializer_class(self):
        return MerchantEightEightDrawListModelSerializer

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        prize = MerchantEightEightActivityPrize.objects.get(id=instance.win_type)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        if prize.prize_type == 1:
            if not login_id:
                return Response({'error': '请上传领取支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
            if not realname:
                return Response({'error': '请上传领取支付宝账号实名姓名'}, status=status.HTTP_400_BAD_REQUEST)
            if instance.state not in [1, 3]:
                return Response({'error': '奖励状态有误'}, status=status.HTTP_400_BAD_REQUEST)
            if instance.state == 3:
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                instance.partner_trade_no = out_biz_no
                instance.save()
            instance.state = 5
            instance.login_id = login_id
            instance.realname = realname
            instance.channel_id = 11
            instance.save()
            alipay_obj = C_AlipayOpen()
            trans_amount = str(instance.amount)
            order_title = instance.desc
            out_biz_no = instance.partner_trade_no
            identity = login_id
            result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                instance.return_msg = result['sub_msg']
                instance.state = 3
                instance.received_time = datetime.datetime.now()
                instance.save()
                return Response({'error': f'领取失败{result["sub_msg"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                instance.received_time = result['trans_date']
                instance.payment_no = result['pay_fund_order_id']
                instance.state = 2
                instance.save()
                try:
                    check_activity = MerchantEightEightActivity.objects.get(activity_id=instance.activity_id)
                    check_activity.total_amount += instance.amount
                    check_activity.save()
                except:
                    pass
                return Response({'success': '领取成功'}, status=status.HTTP_200_OK)
        elif prize.prize_type == 2:
            if not login_id:
                return Response({'error': '请上传领取支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
            if instance.state not in [1, 3]:
                return Response({'error': '奖励状态有误'}, status=status.HTTP_400_BAD_REQUEST)
            if instance.state == 3:
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                instance.partner_trade_no = out_biz_no
                instance.save()
            alidiscountcouponinfo_set = AliDiscountCouponInfo.objects.filter(id__in=json.loads(instance.alidiscountcouponinfo_list), status__in=[0, 14])
            for alidiscountcouponinfo in alidiscountcouponinfo_set:
                alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
                if alidiscountcouponinfo.status == 14:
                    if alidiscountcouponinfo.coupon_channel != 5:
                        out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                    else:
                        out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%04d" % randint(0, 9999)}'
                    alidiscountcouponinfo.out_biz_no = out_biz_no
                    alidiscountcouponinfo.save()
                alipay_obj = C_AlipayOpen()
                template_id = alidiscountcouponinfo.alidiscountcoupon.template_id
                out_biz_no = alidiscountcouponinfo.out_biz_no
                result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
                if result['code'] != '10000':
                    alidiscountcouponinfo.status = 14
                    alidiscountcouponinfo.login_id = login_id
                    alidiscountcouponinfo.return_msg = result['sub_msg']
                    alidiscountcouponinfo.save()
                    instance.return_msg = result['sub_msg']
                    instance.state = 3
                    instance.received_time = datetime.datetime.now()
                    instance.save()
                    return Response({'error': f'领取失败{result["sub_msg"]}', 'status': ''},status=status.HTTP_400_BAD_REQUEST)
                else:
                    voucher_id = result['voucher_id']
                    if alidiscountcoupon.platform_id == 1:
                        result = json.loads(alipay_obj.voucherquery(voucher_id))
                        alidiscountcouponinfo.voucher_id = voucher_id
                        alidiscountcouponinfo.user_id = login_id
                        alidiscountcouponinfo.login_id = login_id
                        alidiscountcouponinfo.template_id = result['template_id']
                        alidiscountcouponinfo.gmt_active = result['gmt_active']
                        alidiscountcouponinfo.gmt_expired = result['gmt_expired']
                        alidiscountcouponinfo.total_amount = result['total_amount']
                        alidiscountcouponinfo.gmt_create = result['gmt_create']
                        alidiscountcouponinfo.available_amount = result['available_amount']
                        alidiscountcouponinfo.name = result['name']
                        alidiscountcouponinfo.status = 1
                        alidiscountcouponinfo.save()
                    else:
                        gmt_create = datetime.datetime.now()
                        alidiscountcouponchannelcommonvoucher = alidiscountcoupon.alidiscountcouponchannelcommonvoucher
                        if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                            gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                            gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                        elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                            gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                            gmt_active = gmt_create
                        else:
                            gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                            gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                        alidiscountcouponinfo.voucher_id = voucher_id
                        alidiscountcouponinfo.user_id = login_id
                        alidiscountcouponinfo.login_id = login_id
                        alidiscountcouponinfo.template_id = alidiscountcoupon.template_id
                        alidiscountcouponinfo.gmt_active = gmt_active
                        alidiscountcouponinfo.gmt_expired = gmt_expired
                        alidiscountcouponinfo.total_amount = alidiscountcoupon.amount
                        alidiscountcouponinfo.gmt_create = gmt_create
                        alidiscountcouponinfo.available_amount = alidiscountcoupon.amount
                        alidiscountcouponinfo.name = alidiscountcoupon.activity_name
                        alidiscountcouponinfo.status = 1
                        alidiscountcouponinfo.save()
            instance.received_time = datetime.datetime.now()
            instance.state = 2
            instance.save()
            return Response({'success': '领取成功'}, status=status.HTTP_200_OK)


class ExpressTypeModelViewSet(ModelViewSet):

    queryset = ExpressType.objects.all()
    serializer_class = ExpressTypeModelSerializer
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('express_type_name', )

    def choices_expresstype(self, request):
        express_number = self.request.query_params.get('express_number', '')
        url = f'https://alayn.baidu.com/express/appdetail/get_com?num={express_number}'
        response = requests.get(url=url)
        try:
            result = response.json()
            express_type = ExpressType.objects.filter(express_type=result['data']['company']).first()
            if express_type:
                return Response(ExpressTypeModelSerializer(express_type).data, status=status.HTTP_200_OK)
            else:
                return Response({}, status=status.HTTP_200_OK)
        except:
            return Response({}, status=status.HTTP_200_OK)


class MerchantMonthlyBillModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = MerchantMonthlyBillFilter

    def get_queryset(self):
        user = self.request.iser
        receipts_time_begin = self.request.query_params.get('receipts_time_begin', None)
        receipts_time_end = self.request.query_params.get('receipts_time_end', None)
        try:
            if '_mutable' in self.request.query_params.__dict__:
                self.request.query_params.__dict__['_mutable'] = True
        except:
            pass
        if receipts_time_begin:
            try:
                datetime.datetime.strptime(receipts_time_begin, '%Y-%m')
            except:
                raise serializers.ValidationError({'error': '时间格式有误'})
            self.request.query_params['receipts_time_begin'] = f'{receipts_time_begin}-01'
        if receipts_time_end:
            try:
                datetime.datetime.strptime(receipts_time_end, '%Y-%m')
            except:
                raise serializers.ValidationError({'error': '时间格式有误'})
            self.request.query_params['receipts_time_end'] = f'{receipts_time_end}-01'
        queryset = MerchantMonthlyBill.objects.filter(merchant__merchantuser_id=user.id)
        return queryset.order_by('-receipts_time')

    def get_serializer_class(self):
        if self.action == 'list':
            return MerchantMonthlyBillListModelSerializer
        else:
            return MerchantMonthlyBillRetrieveModelSerializer


class AfterSaleApplicationFormModelViewSet(ModelViewSet):

    pagination_class = MyPage

    def get_queryset(self):
        user = self.request.iser
        queryset = AfterSaleApplicationForm.objects.filter(order__merchant__merchantuser_id=user.id).exclude(form_status=4)
        return queryset.order_by('-id')

    def get_serializer_class(self):
        if self.action == 'list':
            return AfterSaleApplicationFormListModelSerializer
        else:
            return AfterSaleApplicationFormRetrieveModelSerializer

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.form_status not in [1, 8]:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        audit_status = self.request.data.get('audit_status', None)
        return_msg = self.request.data.get('return_msg', None)
        order = instance.order
        if order.state != 5:
            return Response({'error': '订单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        if not audit_status:
            return Response({'error': '请上传审核参数'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.form_status == 8:
            if instance.reason_type == 1:
                if str(audit_status) == '2':
                    url = 'https://api.gdwxyf.com/api/refund.do'
                    datetime_now = datetime.datetime.now()
                    order_id = f'{datetime_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                    body = {
                        "program_id": "202316837141378884",
                        "shop_id": order.merchant.ruiyinxinMerchantID,
                        "refund_order_id": order_id,
                        "order_id": order.orderNum
                    }
                    key = '6715C7D4435343BA0459EAEC2334D81B'
                    sign = get_sign(body, key)
                    body['sign'] = sign
                    response = requests.post(url=url, json=body)
                    result = response.json()
                    if result['result_code'] == 'success':
                        refund_order_data = {}
                        refund_order_data['order_id'] = order.id
                        refund_order_data['merchantuser_id'] = user.id
                        refund_order_data['operator_role'] = 4
                        refund_order_data['refund_order_id'] = order_id
                        refund_order_data['refund_transaction_id'] = result['refund_transaction_id']
                        refund_order_data['plat_refund_order_id'] = result['plat_refund_order_id']
                        refund_order_data['refund_money'] = result['refund_money']
                        refund_order_data['refund_procedure_money'] = result['commission']
                        refund_order_data['refund_time'] = datetime.datetime.strptime(result['refund_end_time'], '%Y%m%d%H%M%S')
                        refund_order_data['remark'] = '商户同意退款'
                        RefundOrderInfo.objects.create(**refund_order_data)
                        order.state = 8
                        # order.refund_money += Decimal(result['refund_money'])
                        order.refund_money = order.realpay_amount
                        order.out_refund_no = order_id
                        order.refund_id = result['refund_transaction_id']
                        order.save()
                        instance.form_status = 2
                        # instance.refund_money = result['refund_money']
                        instance.refund_time = datetime.datetime.strptime(result['refund_end_time'], '%Y%m%d%H%M%S')
                        instance.save()
                        return Response({'success': '退款成功'}, status=status.HTTP_200_OK)
                    else:
                        refund_order_data = {}
                        refund_order_data['refund_status'] = 2
                        refund_order_data['operator_role'] = 4
                        refund_order_data['order_id'] = order.id
                        refund_order_data['merchantuser_id'] = user.id
                        refund_order_data['return_msg'] = result['error_msg']
                        refund_order_data['refund_order_id'] = order_id
                        refund_order_data['refund_time'] = datetime_now
                        refund_order_data['remark'] = '商户同意退款'
                        RefundOrderInfo.objects.create(**refund_order_data)
                        instance.form_status = 3
                        instance.return_msg = result['error_msg']
                        instance.save()
                        return Response({'error': f'退款失败,原因:{result["error_msg"]}'}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    if not return_msg:
                        return Response({'error': '请写明拒绝退款原因'}, status=status.HTTP_400_BAD_REQUEST)
                    order.state = instance.order_status
                    order.save()
                    instance.form_status = 11
                    instance.return_msg = return_msg
                    instance.save()
                    OrderAdvance.objects.create(
                        order_id=instance.order_id,
                        status=7,
                        remark='商户驳回申请',
                        merchantuser_id=user.id
                    )
                    return Response({'success': '操作成功'}, status=status.HTTP_200_OK)
            else:
                if str(audit_status) == '2':
                    expired_time = datetime.datetime.now() + datetime.timedelta(days=3)
                    instance.form_status = 5
                    instance.expired_time = expired_time
                    instance.save()
                    return Response({'success': '操作成功'}, status=status.HTTP_200_OK)
                else:
                    if not return_msg:
                        return Response({'error': '请写明拒绝退款原因'}, status=status.HTTP_400_BAD_REQUEST)
                    order.state = instance.order_status
                    order.save()
                    instance.form_status = 11
                    instance.return_msg = return_msg
                    instance.save()
                    OrderAdvance.objects.create(
                        order_id=instance.order_id,
                        status=7,
                        remark='商户驳回申请',
                        merchantuser_id=user.id
                    )
                    return Response({'success': '操作成功'}, status=status.HTTP_200_OK)
        else:
            if str(audit_status) == '2':
                url = 'https://api.gdwxyf.com/api/refund.do'
                datetime_now = datetime.datetime.now()
                order_id = f'{datetime_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                body = {
                    "program_id": "202316837141378884",
                    "shop_id": order.merchant.ruiyinxinMerchantID,
                    "refund_order_id": order_id,
                    "order_id": order.orderNum
                }
                key = '6715C7D4435343BA0459EAEC2334D81B'
                sign = get_sign(body, key)
                body['sign'] = sign
                response = requests.post(url=url, json=body)
                result = response.json()
                if result['result_code'] == 'success':
                    refund_order_data = {}
                    refund_order_data['order_id'] = order.id
                    refund_order_data['merchantuser_id'] = user.id
                    refund_order_data['operator_role'] = 4
                    refund_order_data['refund_order_id'] = order_id
                    refund_order_data['refund_transaction_id'] = result['refund_transaction_id']
                    refund_order_data['plat_refund_order_id'] = result['plat_refund_order_id']
                    refund_order_data['refund_money'] = result['refund_money']
                    refund_order_data['refund_procedure_money'] = result['commission']
                    refund_order_data['refund_time'] = datetime.datetime.strptime(result['refund_end_time'],
                                                                                  '%Y%m%d%H%M%S')
                    refund_order_data['remark'] = '商户同意退款'
                    RefundOrderInfo.objects.create(**refund_order_data)
                    order.state = 8
                    # order.refund_money += Decimal(result['refund_money'])
                    order.refund_money = order.realpay_amount
                    order.out_refund_no = order_id
                    order.refund_id = result['refund_transaction_id']
                    order.save()
                    instance.form_status = 2
                    # instance.refund_money = result['refund_money']
                    instance.refund_time = datetime.datetime.strptime(result['refund_end_time'], '%Y%m%d%H%M%S')
                    instance.save()
                    return Response({'success': '退款成功'}, status=status.HTTP_200_OK)
                else:
                    refund_order_data = {}
                    refund_order_data['refund_status'] = 2
                    refund_order_data['operator_role'] = 4
                    refund_order_data['order_id'] = order.id
                    refund_order_data['merchantuser_id'] = user.id
                    refund_order_data['return_msg'] = result['error_msg']
                    refund_order_data['refund_order_id'] = order_id
                    refund_order_data['refund_time'] = datetime_now
                    refund_order_data['remark'] = '商户同意退款'
                    RefundOrderInfo.objects.create(**refund_order_data)
                    instance.form_status = 3
                    instance.return_msg = result['error_msg']
                    instance.save()
                    return Response({'error': f'退款失败,原因:{result["error_msg"]}'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if not return_msg:
                    return Response({'error': '请写明拒绝退款原因'}, status=status.HTTP_400_BAD_REQUEST)
                order.state = instance.order_status
                order.save()
                instance.form_status = 11
                instance.return_msg = return_msg
                instance.save()
                OrderAdvance.objects.create(
                    order_id=instance.order_id,
                    status=7,
                    remark='商户驳回申请',
                    merchantuser_id=user.id
                )
                return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def receive_goods(self, request):
        user = self.request.iser
        form_id = self.request.data.get('form_id', None)
        if not form_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = self.get_queryset().get(id=form_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.form_status != 9:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.reason_type == 2:
            instance.form_status = 1
            instance.save()
        else:
            instance.form_status = 7
            instance.save()
        OrderAdvance.objects.create(
            order_id=instance.order_id,
            status=4,
            remark='商户确认收货',
            merchantuser_id=user.id
        )
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def deliver_goods(self, request):
        user = self.request.iser
        express_array = self.request.data.get('express_array', None)
        form_id = self.request.data.get('form_id', None)
        if not all([express_array, form_id]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            instance = self.get_queryset().get(id=form_id)
        except:
            return Response({'error': '无效申请单id'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.form_status != 7:
            return Response({'error': '申请单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        order = instance.order
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                for express in express_array:
                    try:
                        ExpressType.objects.get(id=express['express_type_id'])
                    except:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '无效快递类型'}, status=status.HTTP_400_BAD_REQUEST)
                    express_data = {}
                    express_data['express_type_id'] = express['express_type_id']
                    express_data['express_number'] = express['express_number']
                    express, create = Express.objects.get_or_create(defaults=express_data, express_number=express['express_number'])
                    relevance_data = {}
                    relevance_data['order_id'] = order.id
                    relevance_data['express_id'] = express.id
                    ExpressOrderRelevance.objects.get_or_create(defaults=relevance_data, order_id=relevance_data['order_id'], express_id=relevance_data['express_id'])
                instance.form_status = 10
                instance.save()
                OrderAdvance.objects.create(
                    order_id=order.id,
                    status=3,
                    remark='商家重新发货',
                    merchantuser_id=user.id
                )
                # try:
                #     express_send.delay({'id': instance.id, 'express_id': express.id})
                # except:
                #     pass
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return Response({'error': '操作失败'}, status=status.HTTP_400_BAD_REQUEST)
            transaction.savepoint_commit(save_id)
            return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class ExpressModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = ExpressFilter
    search_fields = ('express_number',)

    def get_queryset(self):
        user = self.request.iser
        queryset = Express.objects.filter(expressorderrelevance__order__merchant__merchantuser_id=user.id).distinct().order_by('-id')
        return queryset

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        customer_send = len(queryset.filter(nature=2))
        merchant_send = len(queryset.filter(nature=1))
        nature = self.request.query_params.get('nature', None)
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        self.request.data['merchant_send'] = str(merchant_send)
        self.request.data['customer_send'] = str(customer_send)
        if nature:
            queryset = queryset.filter(nature=nature)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def get_serializer_class(self):
        if self.action == 'list':
            return ExpressListModelSerializer
        else:
            return ExpressRetrieveModelSerializer


class GoodsCommentModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('merchant__name', 'goods__name')
    filter_class = OrderGoodsFilter
    serializer_class = GoodsCommentModelSerializer

    def get_queryset(self):
        user = self.request.iser
        queryset = OrderGoods.objects.filter(is_commented=1, order__merchant__merchantuser_id=user.id).order_by('-id')
        return queryset

